statguy
statguy

Reputation: 1717

ManagedObjectContext save causes NSManagedObject data corruption/invalidation

I have this issue when saving the context. It's intermittent. Half of the time, the context saves properly, and half of it, the members of the object becomes null (and actually nothing is left in the context.

"mylist" is a list of NSManagedObject which belongs to the context under which I'm saving. "result" is always YES, and thus there is no error.

    // prints out results before save
    for (MyObj* obj in mylist) {
        NSLog(@"%p, %@", obj, [obj message]);
    }

    //context save here
    NSError *error;
    BOOL result = [[[Core appDelegate] managedObjectContext] save:&error];
    if (!result) {
        NSLog(@"Save Failed!");
        NSLog(@"report: %@, %@, %@", error, [error userInfo],[error localizedDescription]);
    } else {
        NSLog(@"Save succeeded");
    }

    // prints out results after save
    for (MyObj* obj in mylist) {
        NSLog(@"%p, %@", obj, [obj message]);
    }

The console shows something like:

    0x9af6990, message0
    0x9af8910, message1
    0x9afa390, message2
    0x9afa5a0, message3
    Save succeeded
    0x9af6990, (null)
    0x9af8910, (null)
    0x9afa390, (null)
    0x9afa5a0, (null)

I also tried refetching from the context, and I get 0 objects after the save. This is all being done in the main thread. Any ideas? I'm really stumped at this point.

Upvotes: 0

Views: 225

Answers (1)

Mundi
Mundi

Reputation: 80271

Perhaps you should follow Apple's recommendation demonstrated in numerous code examples and use the usual patterns when getting and setting attributes of subclasses of NSManagedObject. You should declare @properties in the @interface and automate the setting/getting with @dynamic.

@interface MyObj : NSManagedObject 
@property (nonatomic, retain) NSString * message;
@end 

@implementation MyObject
@dynamic message;
@end

If you need custom accessors, just override (NSString *)message in your implementation.

Upvotes: 1

Related Questions