2014-01-05 33 views
0

的醫生說:關於objectWithID的好處:

If the object is not registered in the context, it may be fetched or returned as a fault. This method always returns an object. The data in the persistent store represented by objectID is assumed to exist—if it does not, the returned object throws an exception when you access any property (that is, when the fault is fired). The benefit of this behavior is that it allows you to create and use faults, then create the underlying data later or in a separate context.

我想最後一句:

The benefit of this behavior is that it allows you to create and use faults, then create the underlying data later or in a separate context.

這是否意味着我可以使用objectWithID:與任意ID獲得先存在一個不存在對象的錯誤句柄,然後用ID創建對象?但是,我怎樣才能將一個任意的ID分配給新的對象?

+0

如果保存收到的對象會發生什麼情況? – Wain

+0

您可以正常保存,但沒有任何意義。在下面看到我自己的答案。 – an0

回答

2

一般而言,您可以獲取處理不存在的項目,以便稍後創建該項目。
但是,由於您不知道將分配給項目的ID將在這種情況下不是很有用。

您可以使用obtainPermanentIDsForObjects:error:來獲取對象最終ID,但是,這是一次商店旅行,並且會有性能損失。

您可以使用objectWithID:「預熱」協調器緩存。通過這種方式,您可以在後臺獲取對象,並在另一個上下文中使用此方法,然後訪問這些項目而不會觸及商店(性能要好得多)。

+0

我不認爲「你可以通過任何有意義的方式獲得一個不存在的項目的句柄,以後創建該項目」。請看我自己的回答:http://stackoverflow.com/a/20938757/56149 – an0

+0

你做錯了an0;)他明確提到'obtainPermanentIDsForObjects:錯誤:'---刪除並重新插入=新的ID。順便說一句:他說這也沒有用 –

+0

@ Daij-Djan你如何解釋「稍後創建底層數據」?如果您已經擁有該對象並從對象中獲取ID,那麼您不晚可以先創建數據。 – an0

0

由於每個NSManagedObjectID必須首先來自於滿足NSManagedObject,有沒有辦法創造一個從無到有,唯一可行的辦法「以後創建的基礎數據」是沒有意義的,如下:

NSManagedObjectID *objID = object.objectID; 
[moc deleteObject:object]; 
… 
object = [moc objectWithID:objID]; // Deleted so non-existing 
[moc insertObject:object]; // Kinda of resurrecting the deleted object, but not really since the data are gone only ID is left. So it is creating a new object with the old ID. But what's the point? 
// Fill data into object 
… 
[moc save:NULL]; 
+0

不真實。看到丹的代碼 –

-1

如果使用-objectWithID:,則將返回一個錯誤如果該對象尚未在託管對象上下文中註冊(即僅在該對象尚未被提取且未出錯的情況下)。如果它確實返回錯誤,則不需要執行任何操作來「創建對象」。只需訪問對象的屬性就會自動觸發故障並讓您訪問其數據。您不需要額外的工作來創建額外的對象。

+0

沒有我問。請再次閱讀該問題。您也可以閱讀我自己的答案:http://stackoverflow.com/a/20938757/56149 – an0

+0

與問題無關 –