2009-08-01 15 views

回答

6

獲取

myFloat = 2.34f; 

float myFloatValue; 
object_getInstanceVariable(self, "myFloat", (void*)&myFloatValue); 

NSLog(@"%f", myFloatValue); 

輸出:

2.340000

設置

float newValue = 2.34f; 
unsigned int addr = (unsigned int)&newValue; 

object_setInstanceVariable(self, "myFloat", *(float**)addr); 

NSLog(@"%f", myFloat); 

輸出:

2.340000

-1

它可能裝箱在NSNumber中的值。您可以通過NSLogging返回的ID的類名驗證這一點,就像這樣:

id returnedValue = object_getIvar(self, myIntVar); 
NSLog(@"Class: %@", [returnedValue className]); 

編輯:我發現就是這樣的一個位置另一個問題:Handling the return value of object_getIvar(id object, Ivar ivar)

從我自己的實驗,這樣看來,我原來的設想是不正確的。 int和float以及其他基元似乎是作爲實際值返回的。但是,使用ivar_getTypeEncoding來驗證返回的值是您期望的類型是合適的。

+0

當我嘗試調用[returnedValue的className]我得到警告沒有找到方法className。然後,我嘗試使用object_getClassName(object_getIvar(self,myIntVar))(myIntVar實際上是分配在一個for循環,所以它改變),循環執行一次,然後我最終在GDB,但沒有記錄錯誤。唯一被記錄的值是'零'...想法? – 2009-08-01 20:01:03

+0

@Russel我正在研究它並試驗。如果我想出任何東西,我會編輯我的答案。 – 2009-08-01 21:04:06

+0

Jacob讓它使用object_getInstanceVariable工作,但我仍然很好奇如何讓object_getIvar工作,因爲它明顯更快(http://developer.apple.com/documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html #// apple_ref/c/func/object_getIvar)嘗試在網絡上搜索使用它的示例,但沒有人似乎將它用於基本類型。 – 2009-08-02 04:03:17

-1

您可以使用object_getInstanceVariable直接:(沒有測試過)

void *ptr_to_result; 
object_getInstanceVariable(obj, "intvarname", &ptr_to_result); 
float result = *(float *)ptr_to_result; 
+0

我在第三個參數上得到了不兼容的指針時間....我不太熟悉Obj-C恐怕。文檔說它應該是一個無效的指針,這就像我認爲的ID一樣?在這種情況下,我回到了上述相同的問題.... – 2009-08-01 20:14:07

2

返回的值是從對象正確的位置值;只是不正​​確的類型。對於intBOOL(但不float),你可以只投的指針,intBOOL,因爲指針和整數大小相同,它們都可以轉換爲對方:

(int)object_getIvar(obj, myIntVar) 
3

對於ARC:

通過這個答案的啓發:object_getIvar fails to read the value of BOOL iVar。 您必須投入函數調用object_getIvar才能獲得基本類型的ivars。

typedef int (*XYIntGetVariableFunction)(id object, const char* variableName); 
XYIntGetVariableFunction intVariableFunction = (XYIntGetVariableFunction)object_getIvar; 
int result = intVariableFunction(object, intVarName); 

我已經爲這樣的函數指針的快速定義一個有用的小宏:

#define GET_IVAR_OF_TYPE_DEFININTION(type, capitalized_type) \ 
typedef type (*XY ## capitalized_type ## GetVariableFunctionType)(id object, Ivar ivar); \ 
XY ## capitalized_type ## GetVariableFunctionType XY ## capitalized_type ## GetVariableFunction = (XY ## capitalized_type ## GetVariableFunctionType)object_getIvar; 

然後,你需要指定宏調用基本類型(例如PARAMS(長長,LONGLONG)將適合):

GET_IVAR_OF_TYPE_DEFININTION(int, Int) 

在這之後用於接收INT的函數(或指定)的變量類型變得可用:

int result = XYIntGetVariableFunction(object, variableName) 
相關問題