How exactly would I update an object in Realm? Can't seem to find anything on editing/updating objects. Any ideas? Thanks
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";
}];
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";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With