2012-11-22 30 views
1

子類NSManagedObject我有我MOGenerator產生的3個實體,我希望能夠從他們的objectID核心數據取回從它的objectID

我想這讓他們的一回:

- (void)aMethod: (SpecialEntity1ID *)entityID 
{ 
    //This is a method from MagicalRecord but it doesn't matter(I think...). 
    NSManagedObjectContext *context = [NSManagedObjectContext MR_contextWithParent:[NSManagedObjectContext MR_defaultContext]]; 

    SpecialEntity1 *entity1 = [context objectRegisteredForID:entityID] 
    //But this returns an NSManagedObject so it doesn't work... 
} 

有人可以幫我用ID返回這個對象嗎?

因爲我不知道如何做到這一點我正在解決它通過使NSString作爲參數而不是SecialEntity1ID定義此對象的屬性之一(是唯一的)並獲取對象。

我想回到他的身份證更好,所以有什麼想法?

+1

爲什麼你想找回一個子類對象?你想創建一個對象的新實體嗎?或者檢索核心數據中的特定對象? – Pochi

+0

我想讓它恢復原狀,因爲我想在另一個線程上使用它。而且由於在文檔和其他地方都說ManagedObject不是線程安全的,我們必須使用它們的ID來代替,所以我試圖從它的ID中取回它的ID – ItsASecret

+0

http://stackoverflow.com/questions/5035057/how-to-get-core-data-object-from-specific-object-id這對你有幫助嗎? – iDev

回答

2

你想使用你的NSManagedObjectContext的existingObjectWithID:error:方法和類型轉換返回類型,如果你100%確定它會是什麼。我會保持它的通用性,即讓它返回一個NSManagedObject,然後在其他地方測試它的類,如果你想確定它是否屬於一個特定的類。

- (Object*)retrieveObjectWithID:(ObjectID*)theID 
{ 
    NSError *error = nil; 
    Object *theObject = (Object*)[[NSManagedObjectContext contextForCurrentThread] existingObjectWithID:theID error:&error]; 
    if (error) 
     NSLog (@"Error retrieving object with ID %@: %@", theID, error); 
    return theObject; 
} 
+0

我非常確定這個對象是什麼,非常感謝你! – ItsASecret