Archiving, Unarchiving, and Copying NSManagedObject’s

Core Data is awesome. So awesome I use it in just about every single Cocoa application I write for either Mac OS X or iOS. What makes Core Data so great is that it normally just works. By normally I mean 80% of the time. The other 19% of the time there is a not-so-easy but still simple workaround but still a workaround that doesn’t take long to implement.

Then theres the 1% of cases where Core Data is so frustrating it nearly makes probably others and myself want to either run off a cliff, walk in front of a giant truck, rob an Apple store or commit suicide in any other way possible.

The 1% for me normally comes down to two scenarios. Copying NSManagedObject’s and putting them on the clipboard for copy/cut/paste sweetness.

If you’re in the same boat I have a treat for you today. 6 hours, 2 beers, a little research, a lot of documentation and a bit of programming and testing I created two classes and a category. NSManagedObjectArchiver, NSManagedObjectUnarchiver and a NSManagedObjectCopying category.

These three classes do exactly what you think. They archive managed objects to NSData, unarchive them from NSData and allow you to copy them. They not only work on NSManagedObject’s attributes they also support relationships fully ( including circular ones! ) so you can take a single object archive it and restore it later. They’re also smart though and only archive the object’s once even if it’s in multiple places in the object graph.

I should note these classes are not “extremely” tested and thus may have some quirks.

View Gist @ github

Enjoy, -Robert