Sebastien Peek
Sebastien Peek

Reputation: 2528

NSClassFromString Idea

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 above 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?

Upvotes: 2

Views: 423

Answers (3)

Perception
Perception

Reputation: 80603

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.

Upvotes: 0

EmptyStack
EmptyStack

Reputation: 51374

Yes. Do this.

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

Upvotes: 3

Joshua Smith
Joshua Smith

Reputation: 6621

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).

Upvotes: 0

Related Questions