Search code examples
jsonswiftnsmanagedobjectnskeyedarchiver

Map a multi-level JSON object to NSManagedObject with Hyperolso Sync


I'm using the great Sync from HyperOslo to get a JSON object from an API:

JSON object:

{"user":
  {"name" : "damien",
   "email" : "[email protected]",
   "settings" : 
    { "notification" : "true",
      "secretKey" : "dzadd7z5a7dzd5azd"
    }
  }
}

this is my User object, subclassing NSManagedObject. with the property "settings" as a custom NSObject:

class User: NSManagedObject {
    @NSManaged var name: String?
    @NSManaged var email: String?
    @NSManaged var settings: Settings?
}

this looks impossible! (if something know an other third party framework?)

as the doc, the solution would be to use the Binary Data Type:

enter image description here

... but how build the getter of this property in my model? (i know the getter below has any sense):

 @NSManaged var settings: Settings?{
  return [NSKeyedUnarchiver unarchiveObjectWithData:self.settings];
}

Solution

  • The framework's builder advised me a good alternative solution:

    Why not just create a new Core Data table for the new object?

    1 - Add the entity in core data

    enter image description here

    2 - Create the NSManagedObject Subclass for the entity

    class Setting: NSManagedObject {
        @NSManaged var notification: Bool?
        @NSManaged var notification: String?
    }
    

    3 - set hyper.remoteKey = secretKey in the user Info.

    If your JSON says "secret_key" Sync will map it to secretKey in Core Data. But if your JSON says "secretKey" it doesn't know how to transform it to secretKey because it only does automatic transformations for snake_case. So if you wan to use secretKey from your JSON you need to tell Sync this. You do it by adding hyper.remoteKey (key) and secretKey as value in the user Info.

    enter image description here

    3 - create the "setting" relationship on User (don't forget to add the property in your model)

    enter image description here