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

后端 未结 4 1555
面向向阳花
面向向阳花 2020-12-24 13:41

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\". No

相关标签:
4条回答
  • 2020-12-24 13:47
    id a = [[NSClassFromString(@"MyExampleClass") alloc] init];
    

    use this one this will give you what you want.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-24 14:07

    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.

    0 讨论(0)
  • 2020-12-24 14:07

    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.

    0 讨论(0)
提交回复
热议问题