John Scalo
John Scalo

Reputation: 3401

Why would Realm addOrUpdateObject cause a property to get set to nil?

I have a managed Avatar class and a managed User class. The User class has a reference to the Avatar class:

@interface User : RLMObject
...
@property (nonatomic, retain) Avatar *avatar;
...

The Avatar class looks like:

@interface Avatar : RLMObject
@property (nonatomic, retain) NSString *urlStr;
@property (nonatomic, retain) NSData *imageData;
@end

@implementation Avatar
+ (NSString *)primaryKey {
    return @"urlStr";
}
+ (NSArray *)requiredProperties {
    return @[@"urlStr", @"imageData"];
}
@end

There are cases where a I've fetched a new user (say, from the server) but to avoid re-downloading the avatar, I want to instead grab the existing one out of the database. Seems straightforward, but after getting the existing Avatar reference from the db (using [Avatar objectWithPrimaryKey]) and setting it as the avatar property on User, when I then call addOrUpdateObject on the Realm, the avatar property gets set to nil. No exception thrown or debug log, the property just goes from non-nil to nil. And sure enough the User reference is empty in the db although the Avatar table is still populated.

Some of the code:

Checking for extant avatar:

    if let avatarURLStr = user.avatarURLStr, let avatarURL = URL(string: avatarURLStr) {
        if let dbAvatar = Avatar(forPrimaryKey: avatarURLStr) {
            let newAvatar = Avatar(urlStr: dbAvatar.urlStr, imageData: dbAvatar.imageData)
            user.avatar = newAvatar
        } else {
            if let data = NSData(contentsOf: avatarURL) {
                let avatar = Avatar(urlStr: avatarURLStr, imageData: data as Data!)
                user.avatar = avatar
            }
        }
    }

Adding the user to the db:

            let realm = RLMRealm.default()
            realm.beginWriteTransaction()
            // user.avatar is non-nil here
            realm.addOrUpdate(user)
            // user.avatar is nil here
            try? realm.commitWriteTransaction()

I'm on Realm 2.1.1 for Objective-C (but the project uses both Swift and Obj-C).

Upvotes: 2

Views: 235

Answers (1)

John Scalo
John Scalo

Reputation: 3401

Oy…figured it out. I simplified things for the question a bit and it turns out that one of the objects I was updating had a relationship with another object that had a relationship with another object that had an avatar. And that avatar was nil.

Upvotes: 2

Related Questions