user1283776 user1283776 - 3 months ago 11
Objective-C Question

Check if an object is also of another more specific type?

I am loping an array of object that are of a type. More specific types that inherit this type. How do I check if an object is of a certain more specific type?

In the example below I am trying to check if an animal is also an elephant.

for (NSInteger i = 0; i < allAnimals.count; i++) {
Animal *animal = allAnimals[i];

// Check if animal is Elefant?
}

Answer

You can use isKindOfClass method for it

for (NSInteger i = 0; i < allAnimals.count; i++) {
    Animal *animal = allAnimals[i];

    if([animal isKindOfClass:[Elephant class]])
        NSLog(@"Yes it is an Elephant");
}

I have assumed Elephant as a class here