簡體   English   中英

iOS CoreData中的孤立對象

[英]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實例的最可靠方法是

  1. 為您的實體創建自定義NSManagedObject子類(如果您還沒有的話)。
  2. 覆蓋的setter方法purposePlayer子類。 如果新值是nil,則刪除舊值。

您也可以通過確保在適當的時間調用deleteObject:來處理此問題。 或者,您可以運行清理步驟,在該步驟中,為parentPlayer獲取每個PlayerPurpose nil的parentPlayer並刪除它們。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM