2011-11-23 22 views
6

我有這樣的代碼,需要將它移植到電弧,但我不知道如何:如何在arc中替換class_createInstance?

 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 

怎麼更換呢?

我需要在運行時建立類對象。

回答

1

試試這個:

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

這不會處理extraBytes參數class_createInstance –

+0

使用alloc init時這仍然是必需的嗎? –

+0

如果代碼使用額外的字節,是的。否則,沒有 –

3

最直接的解決辦法是增加具有-fno-objc弧上設置另一個文件,並且具有這就要求class_createInstance()如上面的函數。

1

創建一個分隔的.h/.c文件,並把這樣的東西。

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

#include.h,並調用它。無需爲每個文件添加-fno-bjc-arc開關。