I'm having some thoughts on how to use some core data's NSManagedObject subclasses to handle persistent data and non persistent data.
Let's say you have a recipe app displaying a list of your own recipes from CoreData and in this same app you can search for other users recipes as well. These other users recipes are of course from an API and we don't want to save them into core data. But what we want instead is our recipe detail View Controller to act the same either it is given a persistent recipe or a non persistent recipe. I naturally think that we should then use the same object wrapper around our data and let our View Controller to be blind on the origin of the data.
The problem is that NSManagedObject subclasses cannot be initialized manually and have to be inserted into the context. That's not good for our other users recipes. On the other hand for our own recipes we need these object to be inserted into the context.
I have a couple of solutions in mind but I'd really like to read what you guys think of this issue.
Would you say that this is some implementation issue and should be solved by wrapping both data objects into one single object ? For example by overriding all getters and setters to handle both coredata objects and NSDictionary objects ?
Or is it an architecture issue, and you would solve it by for example nesting NSManagedContext, or using multiple persistent stores (one in memory and the other one Sqlite) ?
Actually you can create NSManagedObject instances without inserting them into a context. Just pass nil
as the managed object context argument. Do something like:
NSEntityDescription *myRecipeEntity = [NSEntityDescription entityForName:@"MyRecipeEntity" inManagedObjectContext:[self managedObjectContext]];
MyRecipeClass *recipe = [[MyRecipeClass alloc] initWithEntity:myRecipeEntity insertIntoManagedObjectContext:nil]];
Now you have a recipe instance that's not in any context.
If you later want to add it to a context:
[[self managedObjectContext] insertObject:recipe];
If you don't want to insert it, just throw it away.
I would likely just use a separate context that you never save, that seems to be the simplest route.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With