Convert a string (“MyExampleClass”) into a class name (MyExampleClass)

匆匆过客 提交于 2019-11-28 21:00:59

问题


I want to convert a string to a class name. Imagine that I have a string, which changes, containing a class name, for example, the string "MyExampleClass". Now, I want to create an object of the class MyExampleClass. I have to get the class name from the string. I want to do something like the following. (Consider the code just as a sketch.)

NSString *classNameStr = "MyExampleClass";
id theClass = [UIClass classFromString:classNameStr];
theClass *myObject = [[theClass alloc] init];

What is the right way to do this?


回答1:


Here's what you'd want:

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

Note that you can't use theClass as a type name (i.e. theClass *myObject). You'll have to use id for that.




回答2:


You want NSClassFromString:

NSString *classNameStr = @"MyExampleClass";
Class theClass = NSClassFromString(classNameStr);
id myObject = [[theClass alloc] init];

You can also use the objc runtime interfaces (e.g. objc_getClass(const char* name), objc_lookUpClass(const char* name)). The former will not load a class. The latter will. That option could be a good thing in some cases.




回答3:


id a = [[NSClassFromString(@"MyExampleClass") alloc] init];

use this one this will give you what you want.




回答4:


If you are trying to build your classes dynamically, I recommend you to better take a look at the factory method design pattern, otherwise you will be loosing track of who builds what and how.

To do so, you can code a class that receives a string and returns a class depending on the input string.

Take a look at the book "Design Patterns: Elements of Reusable Object-Oriented Software" by Erich Gamma; Richard Helm; Ralph Johnson; John Vlissides.



来源:https://stackoverflow.com/questions/4654568/convert-a-string-myexampleclass-into-a-class-name-myexampleclass

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