开发者

NSClassFromString Idea

开发者 https://www.devze.com 2023-03-24 02:08 出处:网络
I\'m currently trying to create objects from the NSClassFromString(NSString *) method. What I want to be able to achieve is the following...

I'm currently trying to create objects from the NSClassFromString(NSString *) method.

What I want to be able to achieve is the following...

NSClassFromString(stringType) *pageController = nil;

Instead of the following...

UIViewController *pageController = nil;

So in other words, instead of using a UIViewController, I want to use the correct class. I want to be able to achieve the 开发者_如何学Pythonabove without having to type the exact class. I would normally write it like the following, but due to expansion of the application, it needs to change.

MPLandscapeImage *pageController = nil;

Is this possible and if so, how can I complete what is needed?


Yes. Do this.

Class cls = NSClassFromString(stringType);
// You have to use id here
id pageController = nil;
// And later
pageController = [[cls alloc] init];


You can't really do that. you can use the id type for this.

However, I would ask what you are trying to accomplish because circumventing the type system is often a Bad Idea(tm).


You are attempting to use generics/templates in Objective C. Ain't gonna work. Use the id type instead, its much more applicable to what you are trying to do.

0

精彩评论

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