Create objective-c class instance by name?

前端 未结 4 1556
深忆病人
深忆病人 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:15

    If you are working with Objective-C without the NeXTstep (OS X, iOS, GNUstep etc) system or you just think this method is cleaner, then you could utilize the Objective-C language runtime library's API. Under Objective-C 2.0:

    #import 
    //Declaration in the above named file
    id objc_getClass(const char* name);
    //Usage
    id c = objc_getClass("Object");
    [ [ c alloc ] free ];
    

    Under the Objective-C (1.0 or unnamed version) you would utilize the following:

    #import 
    //Declaration within the above named file
    Class objc_get_class( const char* name);
    //Usage
    Class cls = objc_get_class( "Test" );
    id obj = class_create_instance( cls );
    [ obj free ];
    

    I haven't tested the 1.0 version, however I have used the 2.0 function in code that is now in production. I personally believe utilizing the 2.0 function is cleaner if available than the NS function as it consumes less space: the length of the name in bytes + 1 ( null terminator ) for the 2.0 API versus the sum of two pointers (isa, cstring), a size_t length (cstring_length), and the length of the string in bytes + 1 for the NeXTSTEP API.

提交回复
热议问题