An NSManagedObject
instance can't meaningfully exist outside of an NSManagedObjectContext
instance, so I wouldn't bother trying to do the NSCoding
dances required to directly serialize and deserialize an NSManagedObject
between 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 via instance.entity.attributesByName.allKeys
(you can use [instance dictionaryWithValuesForKeys:keys]
to get the dictionary of attribute:value pairs) . I would send relationship information as NSURL
-encoded NSManagedObjectIDs
. Don't forget to include the instance managedObjectID
(as an NSURL
) 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 NSCoder
system would do for you, except you would have to use the classForCoder
, replacementObjectForCoder:
and awakeAfterUsingCoder:
along with a custom NSDictionary
subclass to handle all the NSManageObject
-to-NSDictionary
mapping 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 single NSManagedObject
instance with no relationships, it's definitely easier to just do the conversion to a dict and back yourself.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…