Building class names form strings

爱⌒轻易说出口 提交于 2020-01-06 13:30:20

问题


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


来源:https://stackoverflow.com/questions/7391152/building-class-names-form-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!