【问题标题】:How can I replace class_createInstance in arc?如何在 arc 中替换 class_createInstance?
【发布时间】:2012-01-05 05:25:01
【问题描述】:

我有此代码,需要将其移植到 arc,但我不知道如何:

        case FIELDTYPE_OBJECT:
            className = [fieldType substringWithRange:NSMakeRange(2, [fieldType length]-3)];
            rel =  class_createInstance(NSClassFromString(className), sizeof(unsigned));
            Class theClass = [rel class];

            if ([rel isKindOfClass:[DbObject class]]) {
                //Load the record...
                NSInteger Id = [rs intForColumn:[theClass relationName]];
                if (Id==0) {
                    fieldValue = [rel init];
                } else {                    
                    Db *db = [Db currentDb];

                    fieldValue = [db loadById: theClass theId:Id];
                }
            }
            break;

错误是:

error: 'class_createInstance' is unavailable: not available in automatic reference counting mode

如何替换?

我需要在运行时构建类对象。

【问题讨论】:

    标签: xcode4 ios5 automatic-ref-counting


    【解决方案1】:

    最直接的解决方案是添加另一个文件,该文件上设置了 -fno-objc-arc,并且具有调用上述 class_createInstance() 的函数。

    【讨论】:

      【解决方案2】:

      试试这个:

      #include <objc/objc-runtime.h>
      id object = [[NSClassFromString(@"TheClassName") alloc] init];
      

      【讨论】:

      • 不会处理class_createInstance的extraBytes参数
      • 在使用 alloc init 时还需要这个吗?
      • 啊,确实。额外字节是除了通常分配的字节之外的额外字节。 . .刚刚对 Rob Rix 的解决方案进行了投票。
      【解决方案3】:

      创建一个单独的.h/.c 文件并放入类似这样的内容。

      id const
      MyCreateInstanceOfClass(Class const class)
      {
          id      instance    =   class_createInstance(class, 0);
          return  instance;
      }
      

      #include.h,然后调用它。无需为每个文件设置-fno-bjc-arc 开关。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-17
        • 2014-12-17
        相关资源
        最近更新 更多