Correct way to edit or copy a row that has no primary key?

346 views
Skip to first unread message

David Holtkamp

unread,
Jan 7, 2015, 4:21:12 PM1/7/15
to realm...@googlegroups.com
I couldn't find anyway to update a row in a table which has no primary key. This was fine, and I assumed the intention was that I just needed to delete and re-insert the row. However, upon testing, I didn't see anyway to create a new Realm object from a previous one outside of manually copying all the property values. What is the correct way to do this?

This is what I had tried so far:

    [realm beginWriteTransaction];
    [realm addObject:mydog];
    [realm commitWriteTransaction];

    Dog *new_dog = [[Dog alloc] initWithObject:mydog];

    [realm beginWriteTransaction];
    [realm deleteObject:mydog];
    [realm commitWriteTransaction];    

    new_dog.age = 4;

    [realm beginWriteTransaction];
    [realm addObject:new_dog];
    [realm commitWriteTransaction];

Which results in:

*** Terminating app due to uncaught exception 'RLMException', reason: 'Adding a deleted or invalidated object to a Realm is not permitted' ***



Ari Lazier

unread,
Jan 7, 2015, 8:52:05 PM1/7/15
to David Holtkamp, realm...@googlegroups.com
One way to update an object is to fetch it by some identifier and then changing its properties.

In your example you should be able to just do:


[realm beginWriteTransaction];
[realm addObject:mydog];
[realm commitWriteTransaction];

[realm beginWriteTransaction];
mydog.age = 4;
[realm commitWriteTransaction];

I'm not sure why your code is failing. One way that could happen is if your dog object pointed to itself, and once copied new_dog would try to add your deleted dog - but this seems unlikely.

--
Ari Lazier



--
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/9f5af3ce-3fe3-49c2-8b73-bf901578903e%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.



{#HS:64371402-274#}
Reply all
Reply to author
Forward
0 new messages