CoreData: numberOfObjects in Section incorrect

帅比萌擦擦* 提交于 2020-01-24 20:28:06

问题


I'm using CoreData in an iOS app to save a simple list of location objects (name, coordinates). I've run into a situation twice now, after a memory warning, when the CoreData records appear to become corrupt.

Specifically, (in tableView:numberOfRowsInSection:)

NSUInteger numObjects = [[[fetchedResultsController sections] objectAtIndex:section] numberOfObjects];

returns 4 for section == 0.

Then (in tableView:cellForRowAtIndexPath:)

aLocation = [fetchedResultsController objectAtIndexPath:indexPath];

for indexPath [0,3] generates an exception:

NSRangeException: * -[_PFArray objectAtIndex:]: index (3) beyond bounds (3)

i.e. CoreData says there are 4 rows in a table, but then can't return an object for the last row when the table view requests it.

Two questions:

1) Any thoughts on how this might arise and how to prevent it

2) Once it has occurred, is there any means to fix the data problem in code?

Thanks

Stephen


回答1:


The issue appears to have been some inconsistency in the CoreData cache that was causing this - unclear what causes it, as the predicates are never changed. I ended up calling deleteCacheWithName if an exception is ever raised on accessing the last object in the fetchedResultsController. This appears to have resolved the issue (no issues from users in 6 months on this).




回答2:


maybe you need to redo the fetch after the memory warning [fetchedResultsController performFetch] (just a guess)




回答3:


I had the same problem myself. I haven't had time to fully investigate but I was setting up the FetchController on a different scratch managedObjectContext each time I called in to the view.

Setting the cacheName to nil solved the problem for me. It wasn't too much of an issue not having the cache as the amount of data was small.



来源:https://stackoverflow.com/questions/4420155/coredata-numberofobjects-in-section-incorrect

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