Create objective-c class instance by name?

前端 未结 4 1558
深忆病人
深忆病人 2020-11-28 02:30

Is it possible to create an instance of a class by name? Something like:

NSString* className = @\"Car\";
id* p = [Magic createClassByName:className];
[p turn         


        
4条回答
  •  感情败类
    2020-11-28 03:14

    NSClassFromString() runs the risk of mistyping the class name or otherwise using a class that doesn't exist. You won't find out until runtime if you make that error. Instead, if you use the built-in objective-c type of Class to create a variable, then the compiler will verify that the class exists.

    For example, in your .h:

    @property Class NameOfClass;
    

    and then in your .m:

    id object = [[NameOfClass alloc] init];
    

    If you mistyped the class name or if it doesn't exist, you'll get an error at compile time. Also I think this is cleaner code.

提交回复
热议问题