代码之家  ›  专栏  ›  技术社区  ›  suse

如何在Objective-C中动态实例化类

  •  5
  • suse  · 技术社区  · 16 年前

    2 回复  |  直到 16 年前
        1
  •  12
  •   Alex Reynolds    16 年前
    MyClass *myClass = [[MyClass alloc] init];
    OtherClass *otherClass = [[OtherClass alloc] init];
    
        2
  •  12
  •   Rolf Staflin CommonsWare    16 年前

    在iPhone上,如果要创建给定类名的类的实例,可以使用运行时函数objc_lookUpClass。

    #import <objc/objc.h>
    [...]
    NSString *handlerClassName = @"MyHandler"
    id handlerClass = objc_lookUpClass([handlerClassName 
                cStringUsingEncoding:[NSString defaultCStringEncoding]]);
    BaseHandler *handler = (BaseHandler *) [[handlerClass alloc] init];