Search code examples
iosobjective-cclasscasting

Objective-C: Get an objects class and cast the object to it dynamically


Let's say I have a collection of objects of different types/classes, i.e. an NSArray.

I know that all of this objects inherit from NSManagedObject and all of them have a property named "uuid".

Now, I want to loop over this array, retrieve each objects uuid and add it to another array, like this:

NSMutableArray *objectUUIDs = [[NSMutableArray alloc] initWithCapacity:0];
for (NSObject *object in objects) {
    // somehow cast the object to its class, so that I can send get its uuid
}

Actually, I could check for the class by [object class] in an if-else-clause, and cast it respectively, but as I have 30 something classes, I would like to do something more generic, like (in pseudo code):

// give me the object's true class instead of NSManagedObject
// add the object uuid to my objectUUIDs array

Solution

  • As you say all objects are NSManagedObjects and all have a property uuid, you can use Key-Value-Coding

    NSMutableArray *objectUUIDs = [@[] mutableCopy];
    for (NSManagedObject *object in objects) {
        [objectUUIDs addObject: [object valueForKey:@"uuid"]];
    }
    

    or

    NSArray *objectUUIDs = [objects valueForKey:@"uuid"]; 
    

    NSArray's -valueForKey doc


    if you enumerate over an collection of objects of different classes you shouldn't type the enumerated object NSObject, but use either the closest common super class, or id — the generic objective-C object type. The reason is that you can send any message to an object typed with id, and you can do further testing. With other more concrete classes you must ensure a message is under stud by an given method.


    You state

    // give me the object's true class instead of NSManagedObject
    

    The object doesn't change during casting. if you put a instance of MyFabulousManagedObject (subclass of NSManagedObject) in an array, and later you cast it to NSManagedObject, it is actually still an instance of MyFabulousManagedObject