In a toy iOS project, I am using MagicalRecord to setup the CoreData stack in the application delegate. With the following code:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[MagicalRecord setupCoreDataStackWithStoreNamed:@"ToyProject.sqlite"];
[[NSManagedObjectContext MR_defaultContext] setUndoManager:[[NSUndoManager alloc] init]];
...
}
I have a subclass of NSManagedObject which I’m writing (NSRailsManagedObject–I forked NSRails and have added CoreData support), and I’ve given it a saveContext method:
- (void)saveContext {
dispatch_async(dispatch_get_main_queue(), ^{
@try {
NSError *error = nil;
if (![self.managedObjectContext save:&error]) {
NSLog(@"Failed to save core data: %@", [error localizedDescription]);
} else {
NSLog(@"\"Successfully\" saved your data.");
}
}
@catch (NSException *exception) {
NSLog(@"Couldn't save your data! Try again later :(");
}
@finally {
NSLog(@"Look, I don't know what else to tell you, mang.");
}
});
}
When I try to save subclasses of this class using this method, I receive NO errors, and the saving ostensibly succeeds. However, on the next run of the application, none of the data that was present in the previous run is there. If instead the saveContext method contains the following code, it works without a problem:
- (void)saveContext {
[[NSManagedObjectContext MR_defaultContext] MR_save];
}
Furthermore, if I hybridize the two, saving does not persist the data.
- (void)saveContext {
dispatch_async(dispatch_get_main_queue(), ^{
@try {
NSError *error = nil;
if (![[NSManagedObjectContext MR_defaultContext] save:&error]) {
NSLog(@"Failed to save core data: %@", [error localizedDescription]);
} else {
NSLog(@"\"Successfully\" saved your data.");
}
}
@catch (NSException *exception) {
NSLog(@"Couldn't save your data! Try again later :(");
}
@finally {
NSLog(@"Look, I don't know what else to tell you, mang.");
}
});
}
I really don’t know what else to try. Can anyone point me in the right direction?
Well, I’ve never used MagicalRecord, but I doubt your problems have anything to do with it. Unfortunately, you did not give the right information.
Specifically, what is YOUR managed object context? Namely, what does self.managedObjectContext return, and how is that context created?
What is its relationship to the default MR context? I think MR does some thread-specific context mapping so if you are going to use MR, you should just stick with MR.
Basically, if it is the same context, you should be OK, but if its not the same one, you will have to coordinate changes with the others. Also, note if you created it as a child, then the save of a child context only pushes the changes to the parent, it does not save them.
Also, make sure your MOC is not nil… a nil MOC will just do nothing went sent the save: message (or any message for that matter).