SRMR SRMR - 3 months ago 8
Objective-C Question

Update Realm database

I'm trying to update the Realm database, but can't figure it out.

I was using

[realm addObject:info];
, but that would just add the same objects to the Realm database that already existed.

So then I replaced that with
[People createOrUpdateInRealm:realm withValue:info];
but that only add the last item in my array of People information (there are six People, but the Realm database would only show the sixth person information).

Not sure what I'm doing wrong?


@property (nonatomic) NSString *fname;
@property (nonatomic) NSString *lname;
@property (nonatomic) NSString *flName;
@property (nonatomic) NSString *email;
@property (nonatomic) NSString *phone;
@property (nonatomic) NSString *video;
@property (nonatomic) NSString *pdf;
@property (nonatomic) NSString *pKey;

+ (NSString *)primaryKey;


+ (NSString *)primaryKey
return @"pKey";


RLMRealm *realm = [RLMRealm defaultRealm];
for (id item in responseArray) {
[realm beginWriteTransaction];

People *info = [[People alloc] init];
info.fname = item[@"fname"];
info.lname = item[@"lname"];
info.flName = [NSString stringWithFormat:@"%@ %@", item[@"fname"], item[@"lname"]]; = item[@"phone"]; = item[@"video"];
info.pdf = item[@"pdf"];

[People createOrUpdateInRealm:realm withValue:info];
[realm commitWriteTransaction];

comes from data from an API.

Let me know if there's any other specific code I should add to help, thanks!


You don't provide the definition of the +primaryKey method, but my suspicion is that your pKey property is your primary key. You're not setting the pKey property on the info object you create, which results in it being left at its default value of nil. This means +createOrUpdateInRealm:withValue: sees you asking to update the same object each time through the loop: the object with a primary key of nil.

Setting the pKey property on info before calling +createOrUpdateInRealm:withValue: should result in all of the objects being saved as you expect.

Note also that it's preferable to minimize the number of write transactions, as each write transaction has a certain amount of overhead. In this case you can easily move the write transaction outside of the loop.