I have several types os root view controller that I want to instantiate one at a time (once per function call). I want to create a property and assign it to this newly created viewcontroller. The problem obviously is that this property will have to be of a specific type dependent on the viewcontroller it is instantiating...
Is there a way to create a generic pointer to overcome this....
There is indeed a generic pointer type; it is id
:
typedef struct objc_object {
Class isa;
} *id;
Which is defined in objc.h, part of the runtime. You can assign any object to a pointer of type id
:
id myString = [[NSString alloc] init];
id myArray = [[NSArray alloc] init];
id myNumber = [[NSNumber alloc] init];
It's also possible, when programming in Cocoa, to use NSObject *
as a sort of generic pointer; since it is the primary root class, nearly every object inherits from it. There's not much gained from doing that, however (in fact, you'll start getting "May not respond to" compiler warnings), and it's not idiomatic.
In general, it is best to type your variables as specifically as possible. In this case, since all the objects will be some kind of view controller, I would recommend using UIViewController *
as the variable type. Then any object which inherits from UIViewController
can be assigned to that pointer, and you still allow the compiler to do type checking.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With