SRMR SRMR - 4 months ago 18
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?

People.h:

@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;


People.m:

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


TableViewController.m:

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"]];
info.phone = item[@"phone"];
info.video = item[@"video"];
info.pdf = item[@"pdf"];

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


The
responseArray
comes from data from an API.

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

Answer

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.

Comments