开发者

create subclass dynamically iphone

I am in the middle of creating some generic class.

And I create three view-controller and I create a enum

typedef enum T开发者_JS百科ype {
    type1,
    type2,
    type3,
} Type;

and for three different type I need to use different view-controllers subclass. But the user feels like one. (what I mean is I can provided it with an interface in that interface class we need to decide which controller used).

I try like this, I create a class and override the init method like follows,

- (id)initWithReaderType:(ReaderType )readerType    {

        switch (readerType) {
            case 0: {
                Slider *slider = [[Slider alloc] init];
                return slider;
            }
            case 1: {
                //use other controller
                break;
            }
            default:    {
                NSLog(@"Exception on Initialization : Un Recognized Reader Type");
                break;
            }
        }

    return nil;
}

But it returns as id object, So I can't use it as a view-controller object and I don't get access to the properties and methods of that controller class.

How Can I achieve this?

thanks in advance....


You can just cast the id (pointer) to an UIViewController (or any of it's subclasses).

id result = [self initWithReaderType:type1];
// Check if we can cast.
if ([result isKindOfClass[UIViewController class]]) {
   UIViewController *viewController = (UIViewController *)[self initWithReaderType:type1];
}

You can change the UIViewController to your own class.


I think you can cast to the type which you want. For example:

Slider *incomeSlider = (Slider *)[self initWithReaderType:type1];

You can try in this way.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜