Dynamically instanting classes in Objective-C, possible? Dynamically instanting classes in Objective-C, possible? xml xml

Dynamically instanting classes in Objective-C, possible?


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

id obj = [[NSClassFromString(@"MySpecialClass") alloc] init];


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]];


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