EXC_BAD_ACCESS on NSManagedObjectContext save meth

2019-02-16 14:20发布

I have found some problems when saving NSManagedObjectContext inside NSOperation with turned on ARC. Without ARC everything was fine before. It is always gives EXC_BAD_ACCESS during saving. The code looks like this:

//on the main thread
-(void)someFunc
{
    array = ... //fetching an array of entities from a core data
    for(SomeEntity * obj in array)
    {
         NSSomeOperation * op = [[NSSomeOperation alloc] initWithValue:[obj someField]];
         //start an operation
    }
}

//NSSomeOperation implementation
//...
- (void)main {
    //some code
    NSError * error = nil;
    [mainContext lock];
    if (![mainContext save:&error]) {    //<--- HERE EXC_BAD_ACCESS
       //process error
    }      
    [mainContext unlock];
    //some code
}
//...

Using of [mainContext setRetainsRegisteredObjects:YES] and objectWithID don't resolve this issue.

EXC_BAD_ACCESS (code=1)
EXC_BAD_ACCESS (code=13)

-[__NSCFType contextDidSave:]: unrecognized selector sent to instance 0x7fc5c505d940

An observer of NSManagedObjectContextDidSaveNotification illegally threw an exception.

Objects saved = {
    inserted = "{(\n)}";
    updated = "{(\n    <SomeEntity: 0x7fc5c55b6220> (entity: SomeEntity; id: 0x7fc5c5052b20 ... )}"; } 
and exception = -[__NSCFType contextDidSave:]: unrecognized selector sent to instance 0x7fc5c505d940 with userInfo = (null)

I use a separate managed object context and fetch my managed objects inside this NSOperation.

Maybe it is something related to Core Data bugs or ARC? Maybe ARC cleans some of objects, that must be saved? Because, without ARC everything was fine, all worked. When I turned on ARC - EXC_BAD_ACCESS.

Does anyone know why it occurs?

1条回答
可以哭但决不认输i
2楼-- · 2019-02-16 14:57

Maybe ARC deallocates some object that receives NSManagedObjectContextDidSaveNotification and this causes the exception? I had something similar, and fixed it by making sure to removeObserver: before the object gets deallocated.

Note that the CoreData exception actually hides the notification center exception, so you don't get to see it.

查看更多
登录 后发表回答