Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically instanting classes in Objective-C, possible?

Tags:

My problem is the following. I have a method which simply takes an XML excerpt and an XPath. It then should create me an array of objects for that XML excerpt. Meaning if I get passed the following XML:

<user>   <name>Bob</name>   <age>50</age> </user> 

My method will instantiate an instance of the class User and use key-value-coding to set the instance variables. It's rather straight forward. The only problem is I come from mostly a scripting background and trying to see if it's possible to pass the method a class name. Right now it's doing a User class, later it might be a Cars class, and then a Home class. What's the best way to instantiate objects from this method of different type while keeping the code as abstract as possible?

like image 728
Coocoo4Cocoa Avatar asked Dec 19 '08 18:12

Coocoo4Cocoa


1 Answers

For instantiating a class using its name, you can use NSClassFromString:

id obj = [[NSClassFromString(@"MySpecialClass") alloc] init]; 
like image 183
codelogic Avatar answered Oct 23 '22 08:10

codelogic