Jasper Chan Jasper Chan - 14 days ago 6
Objective-C Question

Unable to consistently update nested objects in Realm

I'm trying to do some simple updates in a nested object and I'm noticing that its not happening consistently.

Lets hypothetically assume the following classes are involved:

@interface Dog : RLMObject
@property NSString *name;
@property NSData *picture;
@property NSInteger age;
@end

@interface Person : RLMObject
@property NSString *name;
@property RLMArray<Dog *><Dog> *dogs;
@end


If the server passes me a Person object with an updated dog name, currently I would just do (in Psuedocode)

for (Dog *dog in person.dogs)
{
dog.name = updatedDogName;
}

[defaultRealm beginWriteTransaction];
[defaultRealm addOrUpdateObject:person];
[defaultRealm commitWriteTransaction];


ASSUMPTIONS:

1) Person and the respective Dog object has unique primary keys

2) Person and the respective Dog object has already persisted in the DB, and I am merely updating the Dog object through the Person object.

Am I doing something wrong here? I've noticed the update happens roughly half the time only.

Answer

Problem stems from calling writeCopyToURL while an object with a Realm instance attached to it is in use (e.g. person.realm != nil). Use autoreleasepools more liberally to try to lessen the odds of things like this happening.