Objective-C - determining the type of a class at runtime

The interface has the following:

Animal* myPet; 

At runtime, I may want myPet to be a cat or 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 not true, but I hope it is enough to show what I'm trying to do. What is the best practice for this?

+4
source share
4 answers

Strictly enter newPet as Animal * instead of id . id can contain a reference to an instance of any class, but properties cannot be used with it (for dot syntax, a strongly typed lvalue value is required.) Since both Cat and Dog inherit from Animal , this will be completely correct and reliable.

If you use two classes that do not have a common ancestor (the NSObject past), then you should take a step back and rethink your design - why should instances of these two classes occupy the same variable?

+8
source

isKindOfClass is your friend:

 [newPet isKindOfClass:Dog.class] == NO 
+9
source
 NSString *className = @"Cat"; Animal *myPet = [[NSClassFromString(className) alloc] init]; 

It's not clear what you need, but if you want to instantiate a class called a string, that should do it.

+3
source

For those coming from Google based on the heading: β€œDetermine the type of class at runtime,” here are a few useful things to know:

You can call the class method at runtime NSObject* to get a reference to its class.

 [myObject class]; 

See also these methods:

  • isKindOfClass: - check if the object belongs to the class anywhere in its hierarchy.
  • isMemberOfClass: - check if the object belongs to a specific class.
+2
source

Source: https://habr.com/ru/post/1334602/


All Articles