45

I was wondering if i could create a object of some class if i have the name of the class in a NSString. I know this is possible in other languages like ActionScript, C# and PHP...

Something like this:

NSString *className = @"AwesomeViewController";
UIViewController *object = [[className alloc] initWithNibName:className bundle:nil];

1 Answer 1

105

Classes are first-class objects in Objective-C too. You can get the class object from an NSString with the NSClassFromString function.

[[NSClassFromString(className) alloc] init...]
Sign up to request clarification or add additional context in comments.

4 Comments

and the other way around is: NSLog(@"%@", NSStringFromClass([obj class]));
Is it a weak response?
Is there a way to declare a variable using NSString too? I mean if in original poster's post, I don't want to write UIViewController in UIViewController *object but declare it base on NSString. Would that be possible?
You can just use id @huggie. Since the compiler won't know the class, you will get the same result.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.