Home > Objective C > Create a class from a string

Create a class from a string

I found myself in the position that I had a string that came in from XML and wanted to create an appropriate class from this string. After some searching I found the neat little function NSClassFromString. So given a string I could allocate a class by doing

id newClass = [[NSClassFromString(string) alloc] init];

I also needed to go back the other way, get the name of the class as a string. Again there is a similar function definition

NSString* name = NSStringFromClass([self class]);

This above shows how to get the class from self using [self class].

Categories: Objective C Tags:
  1. No comments yet.
  1. No trackbacks yet.