Iphone Core Data crashing on Save

前端 未结 7 722
执念已碎
执念已碎 2020-12-03 06:01

I\'m currently writing an Iphone application using Core Data and I get a EXC_BAD_ACCESS error during the [managedObjectContext save:&&error] code line.

相关标签:
7条回答
  • 2020-12-03 06:06

    You are only guaranteed to retain access to a managed object from the context as long as a change is pending to that object (insert, update, delete). As soon as you make a call to save:, you can lose your reference to the managed object.

    While you stopped getting the error when you set setRetainsRegisteredObjects:YES, you may have introduced a memory management issue, as you are setting the managed object's lifetime to be dependent on the lifetime of the managed object context. If you're passing your context around throughout your app, this could get rather large if you have a large object hierarchy.

    You can read more in the Apple docs here: http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CoreData/Articles/cdMemory.html.

    0 讨论(0)
  • 2020-12-03 06:15

    You must set the FRC cache to nil

    0 讨论(0)
  • 2020-12-03 06:18

    I have seen many funny behaviours with CoreData on iPhone that were solved by resetting content and settings in the iPhone simulator.

    0 讨论(0)
  • 2020-12-03 06:22

    Solved the problem though I'm not sure I'm addressing the actual root cause. The error was eliminated when I added this line:

    [managedObjectContext setRetainsRegisteredObjects:YES];
    

    To where I create the managedObjectContext. So I guess it had to do with retain counts. I'm guessing that maybe instance variables get released partially or temporarily or something when modal views are presented? I don't know. In any case, this error was eliminated the the program works fine now.

    0 讨论(0)
  • 2020-12-03 06:22

    Just to help others having the same issue, and reinforcing Steff's response above, the likely cause of this error is that you are trying to release a NSManagedObject.

    0 讨论(0)
  • 2020-12-03 06:22

    I have solved a similar problem by making sure that the object is fetched, so for the example above:

    if ( message == nil ) {
        message = [NSEntityDescription insertNewObjectForEntityForName:@"MailMessage" inManagedObjectContext:self.managedObjectContext];
    } else {
        NSError *error = nil;
        message = (MailMessage *)[managedObjectContext existingObjectWithID:[message objectID] error:&error];
    }
    
    0 讨论(0)
提交回复
热议问题