Building class names form strings

2019-09-14 23:41发布

问题:

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.

回答1:

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