Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create object from NSString of class name in Objective-C

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]; 
like image 449
Sveinn Fannar Avatar asked Jun 01 '10 17:06

Sveinn Fannar


People also ask

What is NSString in Objective-C?

(NSString *) is simply the type of the argument - a string object, which is the NSString class in Cocoa. In Objective-C you're always dealing with object references (pointers), so the "*" indicates that the argument is a reference to an NSString object.

Is NSString UTF 8?

An NSString object can be initialized from or written to a C buffer, an NSData object, or the contents of an NSURL . It can also be encoded and decoded to and from ASCII, UTF–8, UTF–16, UTF–32, or any other string encoding represented by NSStringEncoding .


1 Answers

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...] 
like image 107
kennytm Avatar answered Sep 20 '22 20:09

kennytm