Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective C - determine class type at runtime

In the interface I have this:

Animal*     myPet;

At runtime I may want myPet to be a cat or a dog, which are subclasses of Animal:

    id newPet;
    if(someCondition) {
            newPet = [[Cat alloc] initWithNibName:@"Cat" bundle:nil];
    } else {
            newPet = [[Dog alloc] initWithNibName:@"Dog" bundle:nil];
    }
    self.myPet = newPet;

Obviously this is incorrect, but I hope it's enough to show what I'm trying to do. What is the best practice for doing this?

like image 981
sol Avatar asked Jan 06 '11 23:01

sol


1 Answers

isKindOfClass is your friend:

[newPet isKindOfClass:Dog.class] == NO
like image 170
jsadfeew Avatar answered Nov 12 '22 06:11

jsadfeew