Prevent Realm from overwriting a property when updating an Object

前端 未结 3 1196
余生分开走
余生分开走 2021-02-05 04:54

I\'ve setup a REST API to realm object in iOS. However I\'ve found an issue with creating a favorite flag in my object. I\'ve created a favorite bool, however everytime the obje

3条回答
  •  我在风中等你
    2021-02-05 05:40

    4. NSUserDefaults (or any other data store, really)

    I ran into the same issue and I opted for the other, more traditional option of saving things to another data store (NSUserDefaults). In my case, I was storing the last time a user viewed an item and storing this data in NSUserDefaults felt appropriate. I did something like the following:

    First, define a unique key for the object you are storing (self here is the model object being viewed and rendered):

    - (NSString *)lastViewedDateKey {
        // Note each item gets a unique key with _ guaranteeing us uniqueness
        return [NSString stringWithFormat:@"%@_%ld", self.class.className, (long)self.itemId];
    }
    

    Then, when a user views the item, set the key to:

    - (void)setLastViewedToNow {
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        [userDefaults setObject:[NSDate date] forKey:self.lastViewedDateKey];
        [userDefaults synchronize];
    }
    

    Later, I use it like this:

    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSDate *createdOnDate = ;
    NSDate *lastViewedDate = [userDefaults objectForKey:self.lastViewedDateKey];
    if (!lastViewedDate || [createdOnDate compare:lastViewedDate] == NSOrderedDescending) {
        ...
    }
    

    As opposed to the above solutions: 1. There is no data persistence. 2. This creates yet another place where one has to define the properties of an object and will likely lead to errors if one forgets to update this list every time a new property gets added. 3. If you are doing any large batch updates, going back through every object is not really practical and will certainly cause pain down the road.

    I hope this gives someone another option if they need it.

提交回复
热议问题