sol
sol

Reputation: 6462

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?

Upvotes: 6

Views: 6687

Answers (4)

Senseful
Senseful

Reputation: 91641

For anyone arriving from Google based on the title: "Determine class type at runtime", here are some useful things to know:

You can call the class method on an NSObject* at run time to get a reference to its class.

[myObject class];

Take a look at these methods too:

  • isKindOfClass: - check if an object belongs to a class anywhere in its hierarchy.
  • isMemberOfClass: - check if an object belongs to a specific class.

Upvotes: 2

Jonathan Grynspan
Jonathan Grynspan

Reputation: 43472

Strongly type newPet as Animal * instead of id. id can hold a reference to an instance of any class, but properties cannot be used with it (the dot syntax requires a strongly typed lvalue.) Since both Cat and Dog inherit from Animal, this will be perfectly correct and valid.

If you're using two classes that don't share a common ancestor (past NSObject), then you should take a step back and rethink your design--why would instances of those two classes need to occupy the same variable?

Upvotes: 8

Alex Wayne
Alex Wayne

Reputation: 186984

NSString *className = @"Cat";
Animal *myPet = [[NSClassFromString(className) alloc] init];

It's unclear what you are after, but if you want to create an instance of a class named by a string, this should do it.

Upvotes: 3

jsadfeew
jsadfeew

Reputation: 2297

isKindOfClass is your friend:

[newPet isKindOfClass:Dog.class] == NO

Upvotes: 10

Related Questions