This is for an iPhone App, but I don’t think that really matters. I need to send a custom object (which is managed by Core Data) over bluetooth using the iPhone’s GameKit. Normally, I would just use an NSKeyedArchiver to package up the object as a data object and ship it over the line, then unarchive the object and I’m done. Of course, I would need to implement the initWithCoder: and encodeWithCoder: methods in my custom object as well.
I’m not sure if this can be done with an NSManagedObject class, which is managed by Core Data or not. Will they play nice together? I’m guessing once I ship the encoded managed object over to the other device and unencode it, I would just add this received object to the other device’s context. Is this correct? Am I missing any steps?
An
NSManagedObjectinstance can’t meaningfully exist outside of anNSManagedObjectContextinstance, so I wouldn’t bother trying to do theNSCodingdances required to directly serialize and deserialize anNSManagedObjectbetween two contexts (you can do this; see below). Instead I would create a dictionary with the appropriate attribute key/values (you can get the attribute names via the managed object instance’s attribute names viainstance.entity.attributesByName.allKeys(you can use[instance dictionaryWithValuesForKeys:keys]to get the dictionary of attribute:value pairs) . I would send relationship information asNSURL-encodedNSManagedObjectIDs. Don’t forget to include the instancemanagedObjectID(as anNSURL) in the dictionary so that you can reconnect any relationships to the object on the other end. You’ll have to recursively create these dictionaries for any targets of relationships for the instance you’re encoding.Then send the dict(s) across the wire and reconstitute them on the other end as instances in a new managed object context (you can use
setValuesForKeysWithDictionary:).You may notice that this is exactly what the
NSCodersystem would do for you, except you would have to use theclassForCoder,replacementObjectForCoder:andawakeAfterUsingCoder:along with a customNSDictionarysubclass to handle all theNSManageObject-to-NSDictionarymapping and visa versa. This code is more trouble than it’s worth, in my experience, unless you have a complex/deep object graph that you’re trying to serialize. For a singleNSManagedObjectinstance with no relationships, it’s definitely easier to just do the conversion to a dict and back yourself.