Oscar Peli
Oscar Peli

Reputation: 1128

A strange iPhone CORE DATA error behavior

I have a really strange behavior in a Core Data app. This is the code:

        unaReg.valore = [NSNumber numberWithInt:val];
        NSError *error;
        if (![managedObjectContext save:&error]) {
            [myUtil manageError:[error localizedDescription]];
        }

unaReg is a Core Data Entity and I want to update its valore property. When I run the save command (managedObjectContext save:&error) I get an error since the program flows inside the if branch. The strange behavior is that the error variable is nil and the new value is saved correctly inside the database (so it seems that there is not an error). What's wrong???? Thanks.

Upvotes: 0

Views: 269

Answers (3)

Hoang Pham
Hoang Pham

Reputation: 6949

If the managedObjectContext is not null, then you may need to check other managed objects that you stored in your managedObjectContext as well. Sometimes, the error might be located in the deletion of some other objects, when you just need to save your unaReg object.

What I usually do are:
- Check your data models on the Delete rule, make sure that you have correctly configured all of them - On your save action of managedObjectContext, ensure that other objects are in some way deleted due to the Delete rule.

Some other situation that I have encountered but right now I can not think of.

Hope it helps

Upvotes: 0

Marcus S. Zarra
Marcus S. Zarra

Reputation: 46718

You need to set NSError *error = nil; to be safe otherwise you are going to get an undetermined memory location assigned.

Like gerry3 mentioned, you probably have a nil managedObjectContext. I would recommend changing the code to:

unaReg.valore = [NSNumber numberWithInt:val];
NSError *error = nil;
NSAssert(managedObjectContext != nil, @"Context is nil");
if (![managedObjectContext save:&error]) {
    [myUtil manageError:[error localizedDescription]];
}

This is a perfect use for NSAssert statements, because you can use them to test inline while developing and with one switch, turn them all off for production.

If your managedObjectContext is nil then you will get a false response from -save: and because you did not set error to nil it will be pointing to "something" in memory, further causing confusion.

Upvotes: 4

gerry3
gerry3

Reputation: 21460

Double check that your managed object context is set:

    unaReg.valore = [NSNumber numberWithInt:val];
    NSError *error;
    NSLog(@"moc = %@",managedObjectContext);
    if (![managedObjectContext save:&error]) {
        [myUtil manageError:[error localizedDescription]];
    }

Upvotes: 1

Related Questions