1

I have 3 entities that I generated with MOGenerator, I'd like to be able to get one of them back from their objectID

I tried this :

- (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...
}

Could someone help me get this object back with its ID ?

Since I don't know how to do it with the ID I'm currently working around it by making a method with an NSStringas a paramater instead of SecialEntity1ID that defines one of the attribute of this object (and is unique) and fetching the object.

I think getting back with his ID is better so any idea ?

Kate Gregory
  • 18,808
  • 8
  • 56
  • 85
ItsASecret
  • 2,589
  • 3
  • 19
  • 32
  • 1
    why do u want to get back a subclassed object? Do you want to create a new entity of an object? or retrieve a specific object within core data? – Pochi Nov 22 '12 at 21:22
  • I want to get it back, because I want to do something with it on another thread. And since in the documentation and everywhere else it's said that ManagedObject are not thread safe, we have to use their ID instead so that's why I'm trying to get it back from its ID – ItsASecret Nov 22 '12 at 21:25
  • http://stackoverflow.com/questions/5035057/how-to-get-core-data-object-from-specific-object-id Is this of any help to you? – iDev Nov 22 '12 at 21:26
  • Not really I saw this question already but in this question he's using NSManagedObject not a subclass, maybe it should help me but I don't see it, could you show me the path :p ? – ItsASecret Nov 22 '12 at 21:28
  • Well, Looks like you already got the answer.. :) And the answer looks same as the above link also. It is just that you need to do a type cast. – iDev Nov 22 '12 at 21:32
  • Yes thank you very much (and for helping me yesterday too !) =) – ItsASecret Nov 22 '12 at 21:33
  • :) I am just trying to learn new things while helping others. That's all. :) – iDev Nov 22 '12 at 21:36

1 Answers1

2

You want to use existingObjectWithID:error: method of your NSManagedObjectContext and typecast the return type if you are 100% sure what it will be. I'd keep it generic i.e. let it return an NSManagedObject and then test its class elsewhere if you want to determine whether it belongs to a particular class.

- (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;
}
Rog
  • 18,602
  • 6
  • 76
  • 97