Skip to content

Instantly share code, notes, and snippets.

Created May 24, 2013 15:19
Show Gist options
  • Save anonymous/5644255 to your computer and use it in GitHub Desktop.
Save anonymous/5644255 to your computer and use it in GitHub Desktop.
NSCoder implementations for preserving NSManagedObject ObjectIDs as URLs and restoring those objects from a managed object context.
@implementation ACodableManagedObject
+ (id)ObjectWithManagedObject:(NSManagedObject*)obj
{
ACodableManagedObject* codableObj = nil;
if (nil != obj)
{
codableObj = [[ACodableManagedObject alloc] init];
codableObj.url = obj.objectID.URIRepresentation;
}
return codableObj;
}
- (id)initWithCoder:(NSCoder*)aDecoder
{
self = [super init];
if (nil != self)
{
self.url = [aDecoder decodeObjectForKey:@"url"];
}
return self;
}
- (void)encodeWithCoder:(NSCoder*)aCoder
{
[aCoder encodeObject:self.url forKey:@"url"];
}
@end
@implementation AManagedObjectArchiver
+ (NSData*)ArchiveDataFromBlock:(void(^)(AManagedObjectArchiver* archiver))codingBlock
{
NSMutableData* data = [NSMutableData data];
AManagedObjectArchiver* archiver =
[[AManagedObjectArchiver alloc] initForWritingWithMutableData:data];
codingBlock(archiver);
[archiver finishEncoding];
return data;
}
- (void)encodeObject:(id)obj forKey:(NSString*)key
{
if ([obj isKindOfClass:[NSManagedObject class]])
{
ACodableManagedObject* codableObj =
[ACodableManagedObject ObjectWithManagedObject:obj];
[self encodeObject:codableObj forKey:key];
}
else
{
[super encodeObject:obj forKey:key];
}
}
@end
+ (void)UnarchiveData:(NSData*)data
Context:(NSManagedObjectContext*)context
Block:(void(^)(AManagedObjectUnarchiver* unarchiver))decodingBlock
{
AManagedObjectUnarchiver* unarchiver = [[AManagedObjectUnarchiver alloc] initForReadingWithData:data];
unarchiver.context = context;
decodingBlock(unarchiver);
[unarchiver finishDecoding];
}
- (id)decodeObjectForKey:(NSString*)key
{
id obj = [super decodeObjectForKey:key];
if ([obj isKindOfClass:[ACodableManagedObject class]])
{
ACodableManagedObject* codableObj = obj;
NSURL* url = codableObj.url;
NSManagedObjectID* objectId =
[self.context.persistentStoreCoordinator
managedObjectIDForURIRepresentation:url];
obj = [self.context existingObjectWithID:objectId error:NULL];
}
return obj;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment