1

MOGeneratorで生成したエンティティが3つありますが、そのうちの1つを元に戻したいです。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で取り戻すのを手伝ってもらえますか?

IDを使用してそれを行う方法がわからないため、現在、このオブジェクトの属性の1つを定義する(そして一意である)NSString代わりにパラメーターとしてを使用してメソッドを作成し、オブジェクトをフェッチすることで回避しています。SecialEntity1ID

彼のIDを取り戻す方が良いと思うので、何か考えはありますか?

4

1 に答える 1

2

existingObjectWithID:error:NSManagedObjectContextのメソッドを使用し、それが何であるかを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;
}
于 2012-11-22T21:30:22.433 に答える