Core Data: solve a strange EXC_BAD_ACCESS error

断了今生、忘了曾经 提交于 2019-12-05 07:32:23
Vincent Guerci

CoreData is not thread-safe; looks like that's your issue try looking at this SO question

I had a similar issue (EA_BAD_ACCESS on [managedContext save])which was caused by a KeyValueObserver that had not been removed when it should have been. It was quite hard to track down. This meant that I was getting this sort of behaviour even with ARC.

Reset Your Managed Object Context After a Persistent Store Migration

I had similar issues. I also work with a couple of threads, and I use Core Data’s migratePersistentStore:toURL:options:withType:error: function.

In my case the error happened right after a migration in another thread. I thought that my issues were thread-related, so I began to double-down on thread-safety in my code, but in reality a single call to managedObjectContext.reset() before doing any subsequent operations on objects in the managed object context solved all issues.

Core Data Behavior

Strangely enough existingObjectWithID:error: was always giving me back a reference to a non-existing object, so that I was accessing non-existent objects and receiving EXC_BAD_ACCESS. After resetting the context the function exposed the correct behavior.

These two lines are redundant and possibly dangerous:

model.modelA = modelA; // I pass modelA as a parameter to the function
[modelA addModelBObject:model];

The managed object context will automatically sent the reciprocal relationship for you so there is no need to do it manually. In fact, I think it might cause a dangerous loop. You can use just one line or the other and both sides of the relationship will be automatically set. I recommend just:

model.modelA = modelA;

... because it is simpler.

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