Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating an object in Realm

Tags:

ios

realm

How exactly would I update an object in Realm? Can't seem to find anything on editing/updating objects. Any ideas? Thanks

like image 594
mlevi Avatar asked Mar 19 '15 17:03

mlevi


2 Answers

Here is the documentation on updating objects in Realm.

And here is another option to update objects than the one discussed in the other answers.

A lot of times, when I want to update objects, I only really need to update one or two properties, one annoying thing about Realm is property changes of a persisted object need to be wrapped in a write transaction, so I usually add a wrapper method to my objects to clean the interface up a bit:

@implementation SomeRealmClass

    - (void)update:(void (^)(SomeRealmClass *instance))updateBlock
    {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
            RLMRealm *realm = [RLMRealm defaultRealm];
            [realm beginWriteTransaction];
            updateBlock(self);
            [realm commitWriteTransaction];

        });
    }

@end

This way, I can update an object like so:

SomeRealmClass *instance = [[SomeRealmClass allObjects] objectAtIndex:0];

[instance update:^(SomeRealmClass *instance) {
    instance.foo = @"foo 2";
    instance.bar = @"bar 2";
}];
like image 178
Jaymon Avatar answered Oct 28 '22 15:10

Jaymon


You can use the following API from RLMRealm class:

– addOrUpdateObject:
– addOrUpdateObjectsFromArray:

https://realm.io/docs/objc/latest/api/Classes/RLMRealm.html#//api/name/addOrUpdateObject: https://realm.io/docs/objc/latest/api/Classes/RLMRealm.html#//api/name/addOrUpdateObjectsFromArray:

For updating the objects in Realm, you need to define some primary key in your RLMObject subclasses, so that Realm then knows what to update.

+ (NSString *) primaryKey
{
    return @"somePropertyNameAsString";
}
like image 45
gagarwal Avatar answered Oct 28 '22 13:10

gagarwal