0

I create an app with core data on Xcode 3.2.5 and it work fine. But now I install Xcode 4.3.1 and now my data are not saving when I close the app. [context save:&error] - not work any more (it isn't save data). If someone have the same problem please tell how to resolve it.

rowwingman
  • 5,589
  • 7
  • 33
  • 50

2 Answers2

2

It's hard to answer without more details but you should have this kind of method in your app :

- (void)saveContext
{
NSError *error = nil;
NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
if (managedObjectContext != nil)
{
    if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error])
    {
        /*
         Replace this implementation with code to handle the error appropriately.

         abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 
         */
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    } 
}
}

Thus, if there is some error you would get it in console.

Basically, every time you make a change in your data, you should call the saveContext method, not just while you close the app.

Look also for core data evolutions over time, maybe your app was made for another iOS version and your code needs to be updated.

moxy
  • 1,634
  • 1
  • 11
  • 19
0

First of all you check crash logs, you can read the reason of a crash there. I bet in-memory objects cannot be saved because of restriction of you Data Model.

For example, a value of one of object's field is nil but you selected Not Null restriction in Xcode during modeling your database. Inspect your database for this restrictions: not null, additional validation for values (max value, min value, regular expressions for strings and so on).

And add this code after saving:

if (error) {
    NSLog(@"Data cannot be saved: %@", error);
}


UPD As Paul.s say the correct way of checking is:

if (![context save:&error]) {
    NSLog(@"Data cannot be saved: %@", error);
}

More information about handling errors like that presented here

Eldar Markov
  • 950
  • 9
  • 13
  • You check the return of `- (BOOL)save:(NSError **)error` if this returns `NO` then it means it failed and then you should interrogate the error. You never really interrogate the error straight away. – Paul.s Mar 18 '12 at 18:03
  • This [question/answer](http://stackoverflow.com/questions/1808929/handling-nserror-when-reading-from-file) gives a longer description – Paul.s Mar 18 '12 at 18:06
  • Maybe/maybe not in this particular case but that is the pattern that the Apple API's follow so you should stick to it – Paul.s Mar 18 '12 at 18:16