I need to transfer a single object across device. Right now I am converting my NSManagedObject to a dictionary , archiving it and sending as NSData. Upon receiving I am unarchiving it. But I would really like to transfer the NSManagedObject itself by archiving and unarchiving instead of creating an intermediate data object.
@interface Test : NSManagedObject<NSCoding>
@property (nonatomic, retain) NSString * title;
@end
@implementation Test
@dynamic title;
- (id)initWithCoder:(NSCoder *)coder {
self = [super init];
if (self) {
self.title = [coder decodeObjectForKey:@"title"]; //<CRASH
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)coder {
[coder encodeObject:self.title forKey:@"title"];
}
@end
NSData *archivedObjects = [NSKeyedArchiver archivedDataWithRootObject:testObj];
NSData *objectsData = archivedObjects;
if ([objectsData length] > 0) {
NSArray *objects = [NSKeyedUnarchiver unarchiveObjectWithData:objectsData];
}
The problem with the above code is. It crashes at self.title
in initWithCoder
saying unrecognized selector sent to instance.
- Why is
title
not being recognized as a selector. - Should unarchive use a nil managed object context somehow before creating the object in
initWithCoder
? - Do i need to override
copyWithZone
?