[iOS] Core Data Error: 不知道何時被刪掉了

SC Tuan
SC Tuan
Jul 24, 2017 · 2 min read

前言

遇到像這樣的錯誤訊息:

// EXC_BREAKPOINT
CoreData _sharedIMPL_pvfk_core + 304

查了一下,發現似乎是因為managed object要用的時候,被別的線程刪除了,不知道是被系統還是被自己刪掉的,所以使用前要先檢查。

處理

RestKit

由於我是用RestKit去處理core data,這裡面有一個API:

- (BOOL)hasBeenDeleted

這是說你的物件已經被刪除,然後也save到persistent store了,那他就會回傳YES。

Core Data

相對於Core data提供的API

@property (nonatomic, getter=isDeleted, readonly) BOOL deleted;

這是說你把物件刪除了,然後你會在下一次的save時把這更動寫入,那他就會跟你說YES。

另一種檢查的方法是看物件的managedObjectContext還在不在,在NSManagedObject裡面有寫這個property的說明:

May be nil if the receiver has been deleted from its context.

不過也是有可能(May)而已,所以這不是很可靠。

實作

如果單純用Core data裡面的方法去檢查,簡單的寫法就像這樣:

- (BOOL) entityWasDeleted:(SomeEntity *)someEntity {

return ((someEntity == nil) || ([self.moc existingObjectWithID:someEntity.objectID error:NULL] == nil));
}

請參考網路上的解答

SC Tuan

Written by

SC Tuan

iOS developer😘 / Web developer🤪/ anymore? 😎

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade