EXC_BAD_ACCESS on NSManagedObjectContext save method inside NSOperation and ARC, why?

强颜欢笑 提交于 2019-11-30 23:43:08

问题


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:


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.



来源:https://stackoverflow.com/questions/9419048/exc-bad-access-on-nsmanagedobjectcontext-save-method-inside-nsoperation-and-arc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!