开发者

Generic Type In Objective C

I have several types os root view controller that I want to instantiate one at a time (once per function call). I w开发者_开发技巧ant 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.


Thats what id is in Objective-C, a untyped Objective-C object pointer.

id test = [[NSMutableArray alloc] init];

etc

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜