views:

1409

answers:

4

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?

+22  A: 

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

id obj = [[NSClassFromString(@"MySpecialClass") alloc] init];
codelogic
+10  A: 

Classes are objects and can be used/sent the same as other objects.

To create a class object:

Class classForElement = [MyUserClass class];

To instantiate an object of that class

id newObject = [[classForElement alloc] init];

If the class name is not the same as the element name, create a dictionary that has the Class as the object an the element name as the key.

[NSDictionary dictionaryWithObjectsAndKeys:
                         [MyUserClass class], @"user", 
                         [MyCarClass class], @"car", 
                         [MyHomeClass class], @"home",
                          nil]];
Nathan Kinsinger
+1  A: 

You want to take an in-depth look at Core Data. Managed Objects might come to the rescue.

CocoaDevCentral has some introducing articles, but you probably need the Apple docs.

http://cocoadevcentral.com/articles/000086.php

[edit] I just was reminded that you're doing this on an iPhone. Unavailability of the Core Data framework doesn't mean you cannot borrow from it, and just reimplement what you need. One of the open source OpenStep frameworks might have code.

On a mobile device you might want to be careful about the size of your data.

Ezra Epstein on runtime creation of classes (and more):

http://www.macdevcenter.com/pub/a/mac/2002/05/24/runtime_partone.html

Stephan Eggermont
Note the cocoa-touch tag. Core Data doesn't exist on the iPhone.
Peter Hosey
It provides the solution, though. Recreate a minimal subset
Stephan Eggermont
A: 

Try using id as the parameter type in your method signature. An id object can be type-cast into any class object

Are you doing the project for an iPhone. Are you using NSXMLNode. In case you are, please be aware that use of NSXMLNode will only be allowed on the simulator. It will not work on the iPhone as NSXMLNode is a part of the core library.

lostInTransit