的文檔狀態:什麼是「適當的」的方式來使用的NSManagedObjectContext的objectWithID:
...此方法始終返回的對象。 通過的objectID代表持久性存儲 該數據被認爲 存在,如果沒有,則返回 對象拋出一個異常,當你 訪問任何財產(即,當 故障被解僱)。這種 行爲的好處是它允許您創建和使用故障,然後在後面或在單獨的上下文中創建 基礎行。
,並在蘋果的「核心食譜」示例應用程序的方法的結果是用來填充的NSFetchRequest,然後請求的結果時,有意見認爲效果:
// first get the object into the context
Recipe *recipeFault = (Recipe *)[context objectWithID:objectID];
// this only creates a fault, which may NOT resolve to an object (for example, if the ID is for
// an objec that has been deleted already): create a fetch request to get the object for real
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
[request setEntity: [NSEntityDescription entityForName:@"Recipe" inManagedObjectContext:context]];
NSPredicate *predicate = [NSPredicate predicateWithFormat: @"(self == %@)", recipeFault];
[request setPredicate: predicate];
我有看到很多例子(其他的代碼和蘋果的'iClass'),其中objectWithID
的結果被直接使用 - 意思是,它的屬性被訪問和愉快地處理。
應該objectWithID
總是被視爲'也許這存在'的對象?
我在問,因爲我剛剛遇到了這個問題,並沒有提到它的存在。
我想我不理解的是,如果它在某種程度上'更好'或'更適當'做fetchRequest,使用返回的對象來找出它是否存在,或者就像剛纔那樣試圖訪問它的屬性,並返回一個異常,因爲該對象不存在?是後一種,是一種捷徑,還是不明智? – lulu 2011-01-29 23:32:36