[英]Orphaned objects in iOS CoreData
假設我有一個稱為Player
的CoreData實體類型,並且它與一個名為PlayerPurpose
的實體類型具有一對一的關系( purpose
)。 為了完整PlayerPurpose
,假設我們在PlayerPurpose
有一個相反的關系,稱為parentPlayer
。 考慮以下快速代碼:
// Assume we already have a player object in a NSManagedObjectContext called context:
player.purpose = NSEntityDescription.insertNewObjectForEntityForName("PlayerPurpose",
inManagedObjectContext: context) as PlayerPurpose;
// Later in the code, we set the value to nil (or we could have replaced
// it with another call to insertNewObjectForEntityForName)
player.purpose = nil;
// What happens to the previous playerPurpose object within the Managed Object Context?
我的問題:如果托管對象上下文中的原始playerPurpose對象在數據中的唯一引用設置為nil(或替換為另一個對象),將會發生什么?
這與關系刪除規則並沒有真正的關系,因為我沒有明確刪除任何對象,而是將其從任何有意義的關系中刪除,從而使其成為孤立對象。
從ARC的角度來看(如果PlayerPurpose只是一個普通的非托管對象),原始的PlayerPurpose實例現在沒有引用,因此可以從內存中清除它-但是在托管對象上下文中會發生什么? CoreData是否將其識別為孤立對象並通過上下文將其刪除?
如果不是這樣,那么我假設如果要擺脫對它的所有引用,我必須小心刪除通過上下文創建的任何托管對象。 假設是這種情況,是否可以使用一種好的模式來確保從NSManagedObjectContext中清除孤立對象,並且不再將它們存儲在持久性存儲中?
謝謝!
在這種情況下,Core Data不會自動刪除對象,因為“孤立”是您的代碼具有的概念,而Core Data不能識別該概念。 沒有理由僅因為其關系之一為nil來刪除PlayerPurpose
對象。
確保刪除PlayerPurpose
實例的最可靠方法是
NSManagedObject
子類(如果您還沒有的話)。 purpose
的Player
子類。 如果新值是nil,則刪除舊值。 您也可以通過確保在適當的時間調用deleteObject:
來處理此問題。 或者,您可以運行清理步驟,在該步驟中,為parentPlayer
獲取每個PlayerPurpose
nil的parentPlayer
並刪除它們。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.