Re: [realm-cocoa] Can't set primary key property "id" to existing value '123'.'

1,220 views
Skip to first unread message

Adam Fish

unread,
Sep 29, 2015, 12:52:01 PM9/29/15
to Tom, realm...@googlegroups.com
The primary key property name in that error suggests your model is different than you describe. The property name says 'key' not 'id'. Did the model change previously?

--
Adam Fish
Platform Manager


On Mon, Sep 28, 2015 at 2:43 PM UTC, Tom <to...@kamatom.com> wrote:
Hi,

I am scratching my head and not sure what I am doing wrong here so advice would be really appreciated. I have an object with a primary key :

class TheObject: Object {


dynamic var id = 0 //primary key


override
static func primaryKey() -> String?{

//return primary key

return "id"

}


I want to create or update the object :

func createOrUpdate(){

let
object = TheObject()
if let key = json["id"] as? Int { object.id = key }
let realm = try! Realm()


try
realm.write{

realm.add(object, update:true)

}

}


After reading Realm Swift documentation I believe that realm.add(object, update:true) should update the object if it already exist but I get the error *** Terminating app due to uncaught exception 'RLMException', reason: 'Can't set primary key property 'key' to existing value '123'.'

Thanks!



--
You received this message because you are subscribed to the Google Groups "Realm" group.
To unsubscribe from this group and stop receiving emails from it, send an email to realm-cocoa...@googlegroups.com.
To post to this group, send email to realm...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/realm-cocoa/59eb3cb8-6b5d-4f39-9bbc-b84675c99b8a%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.



{#HS:126034604-1946#}

Tom

unread,
Sep 30, 2015, 3:34:20 AM9/30/15
to Realm, to...@kamatom.com, he...@realm.io
Thank you, Adam.You are right  The model was a little more complex and there were more things happening within the realm write than shown here.
 I found that the problem was elsewhere- I was setting Another Realm Object as a property of TheObject. The problem was that AnotherObject() did not have a primary key. Once I added it- the issue was solved. 



The problem was that AnotherObject() did not have a primary key. Once I added it- the issue was solved.  

Adam Fish

unread,
Sep 30, 2015, 1:05:14 PM9/30/15
to Tom, realm...@googlegroups.com
Awesome, glad you figured it out!

Cheers,
Adam


--
Adam Fish
Platform Manager


{#HS:126034604-1946#}

Henry Kim

unread,
Dec 17, 2015, 5:49:20 AM12/17/15
to Realm, to...@kamatom.com, he...@realm.io
has this problem fixed? 

2015년 9월 30일 수요일 오전 1시 52분 1초 UTC+9, Adam Fish 님의 말:

Tom

unread,
Dec 17, 2015, 12:14:59 PM12/17/15
to Realm
Yes. If you have other objects as properties- they all need to have their primary keys. At least that what happened in my case.
Reply all
Reply to author
Forward
0 new messages