Reputation: 1463
How exactly would I update an object in Realm? Can't seem to find anything on editing/updating objects. Any ideas? Thanks
Upvotes: 8
Views: 10702
Reputation: 4244
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";
}
Upvotes: 4
Reputation: 3134
Here is a method I wrote to update my database which has a table called CDlevels.
You can call this method from any thread as it will allocate realm from that thread and do the needful.
-(void)updateLevel:(int)levelNo WithScore:(NSString*)strScore complete:(void (^)(BOOL))completed{
RLMRealm *realm = [RLMRealm defaultRealm];
NSPredicate *pred = [NSPredicate predicateWithFormat:@"levelNo = %d",levelNo];
RLMResults *RLMLevels = [CDLevels objectsWithPredicate:pred];
CDLevels *myLevel = [[CDLevels alloc]init];
myLevel = [RLMLevels objectAtIndex:0];
[realm beginWriteTransaction];
myLevel.score = strScore;
[realm commitWriteTransaction];
completed(YES);
}
This is how you can call this method, say to update level 1 with a score 100
[self updateLevel:1 WithScore:@"100" complete:^(BOOL completed) {
if (completed) {
NSLog(@"score updated");
}
}];
I have tasted this and it works very cool. I am trying to change one of my coredata app to Realm.
Hope this help. If the answer flagged as an answer is wrong please correct it.
This is a primitive method and I believe it can be made better.
cheers
Upvotes: -1
Reputation: 5748
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";
}];
Upvotes: 4
Reputation: 4120
In Realm, whenever you retrieve an object from the database, you can update its properties and those changes will be reflected in the database.
Upvotes: 2