ophychius ophychius - 2 years ago 123
iOS Question

MagicalRecord does not save data

I am trying my hand at some very basic implementation of MagicalRecord to get the hang of it and run into the following.

When I save an entry and then fetch entries of that type it will come up with the entry I just saved. However, when I save the entry, close the app, start it again, and then fetch, it comes up empty.

Code for saving:

- (void)createTestTask{
NSManagedObjectContext *localContext = [NSManagedObjectContext contextForCurrentThread];

Task *task = [Task createInContext:localContext];
task.tName = @"First Task";
task.tDescription = @"First Task created with MagicalRecord. Huzzah!";

NSError *error;
[localContext save:&error];
if (error != Nil) {
NSLog(@"%@", error.description);

Code for fetching: (all I want to know here if anything is actually saved)

- (void) fetchTasks{
NSArray *tasks = [Task findAll];
NSLog(@"Found %d tasks", [tasks count]);

I am sure I am missing something here, but not anything I can seem to find on stackoverflow or in the Tutorials I looked at.

Any help is welcome.

Answer Source

I have to ask the obvious "Is it plugged in" question: Did you initialize the Core Data Stack with one of the +[MagicalRecord setupCoreDataStack] methods?

Did your stack initialize properly? That is, is your store and model compatible? When they aren't, MagicalRecord (more appropriately, Core Data) will set up the whole stack without the Persistent Store. This is annoying because it looks like everything is fine until it cannot save to the store...because there is no store. MagicalRecord has a +[MagicalRecord currentStack] method that you can use to examine the current state of the stack. Try that in the debugger after you've set up your stack.

Assuming you did that, the other thing to check is the error log. If you use

[localContext MR_saveToPersistentStoreAndWait];

Any errors should be logged to the console. Generally when you don't see data on a subsequent run of your app, it's because data was not saved when you thought you called save. And the save, in turn, does not happen because your data did not validate correctly. A common example is if you have a required property, and it's still nil at the time you call save. "Normal" core data does not log these problems at all, so you might think it worked, when, in fact, the save operation failed. MagicalRecord, on the other hand, will capture all those errors and log them to the console at least telling you what's going on with your data.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download