Converting Archived Mantle Models to CoreData equivalents

This is more of a lab report. 😉

I recently published an update to Songbook Simple, where I really made a false assumption and ended up annoying a few users. I assumed that most people would just use the Dropbox functionality, but there are some who don’t and as a result of their update, their songs were seemingly deleted. 😦

Well, I’m happy to say I found a way around it. The problem was I replaced my old data model layer, which was archiving songs using the Mantle Framework (a framework I originally liked but ultimately Core Data is now irreplaceable) with Core Data models. Not wanting to change class names, I just made my classes SBSong and SBArtist inherit from NSManagedObject whereas before they were subclasses of MTLModel, the baseclass of the Mantle Framework.

This poses a problem when loading old data that was archived to disk by supporting the NSCoding protocol (which Mantle does).

It was a lot simpler than I thought. I just supported the NSCoding protocol on my NSManagedObject subclasses, implemented initWithCoder:.

- (id)initWithCoder:(NSCoder*)coder
NSManagedObjectContext *context = [NSManagedObjectContext MR_contextForCurrentThread];
self = [super initWithEntity:[SBSong MR_entityDescriptionInContext:context] insertIntoManagedObjectContext:context];
self.isLegacyFormat = @YES;
// do something with coder here,
NSString *name = [coder decodeObjectForKey:@"name"];
NSString *filename = [coder decodeObjectForKey:@"filename"];
NSDate *modifiedDate = [coder decodeObjectForKey:@"modifiedDate"];
SBArtist *artist = [coder decodeObjectForKey:@"artist"]; // has a similar implementation!
// = name;
self.filename = filename;
self.modifiedDate = modifiedDate;
self.artist = artist;
NSString *mantleText = [self mantleContent];
self.text = mantleText;
// wordpress code formatter sux
return self;

and then an import method that will import all the old songs, mark them as legacy format, then I can create equivalent objects that will be guaranteed to be unique (i.e. one artist object per artist, as this code above would create multiple artists that are the same person)

Anyway, it IS possible to unarchive Mantle-archived objects without having the Mantle Framework in your project anymore. If you need help, drop me a line.



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s