cannyboy
cannyboy

Reputation: 24426

Building class names form strings

I have an array of strings like this:

tableArray: { "Map", "Web", "Help" + 10 other strings}

The array is used to build the table cells in a UITableViewController. When tapped I want the appropriate view controller to show, in the didSelectRowAtIndexPath method.

Instead of creating a large switch, or if .. then .. else statement, can I somehow create the class name from the strings above, so that Map becomes MapViewController:

MapViewController *detailViewController = [[MapViewController alloc] initWithNibName:@"MapViewController" bundle:nil];
[self.navigationController pushViewController:detailViewController animated:YES];
[detailViewController release];

.. and "Web" creates WebViewController etc.

Upvotes: 0

Views: 95

Answers (1)

d.lebedev
d.lebedev

Reputation: 2303

Class theClass = NSClassFromString(classNameStr);
id myObject = [[theClass alloc] init];

Upvotes: 1

Related Questions