Search code examples
iosobjective-cgithub-mantle

Merge two objects of same type


I have two objects:

deviceConfigInfo and deviceStatusInfo

Both contain an array of devices (so theres a third device object actually).

For each device returned in deviceConfigInfo there are these properties:

  • uuid
  • name
  • somethingElse
  • lookAnotherOne

and for deviceStatusInfo

  • uuid
  • name
  • somethingElse
  • someStatusInfo
  • someMoreStuff

(If you hadn't guessed, I just made up some random properties)

So back to that third object I mentioned, device, I created it with all the properties combined. Now, my question is, say the deviceStatusInfo gets updated, how can I update the device object without losing the "old" data that isn't overwritten (in this case, the lookAnotherOne property).

Does it have to be a manual process of getting the device with the matching uuid and then updating each of the properties for deviceStatusInfo or is there a quicker way of doing this? Imagine there were loads of properties.

Hopefully this makes sense. If it helps, I am using Mantle to create the objects/models.


Solution

  • I noticed that Mantle has the following function which I was able to use:

    mergeValueForKey:fromModel:

    So in my device model, I added two functions:

    • mergeConfigInfoKeysFromModel:
    • mergeStatusInfoKeysFromModel:

    These functions have access to an array that contains NSString values representing the properties/keys. There is one array for the configInfo and another for statusInfo properties/keys.

    I then loop through the keys and use valueForKey to check it has an actual value. If it does, I then call the mergeValueForKey:fromModel:.

    Example Code:

    - (void)mergeConfigInfoKeysFromModel:(MTLModel *)model
    {
        NSArray *configInfoKeys = @[@"uuid", @"name", @"somethingElse", @"lookAnotherOne"];
    
        for (NSString *key in configInfoKeys) {
            if ([model valueForKey:key]) {
                [self mergeValueForKey:key fromModel:model];
            }
        }
    }
    

    All I have to do now, is call the appropriate merge function on the device object when I get an update, passing over the updated device object. Just as below:

    [self.device mergeConfigInfoKeysFromModel:deviceUpdate];