Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the int value from object_getIvar(self, myIntVar) as it returns a pointer

if the variable in object_getIvar is a basic data type (eg. float, int, bool) how do I get the value as the function returns a pointer (id) according to the documentation. I've tried casting to an int, int* but when I try to get that to NSLog, I get error about an incompatible pointer type.

like image 994
Russel West Avatar asked Aug 01 '09 18:08

Russel West


2 Answers

Getting:

myFloat = 2.34f;

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

NSLog(@"%f", myFloatValue);

Outputs:

2.340000

Setting:

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

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

NSLog(@"%f", myFloat);

Outputs:

2.340000

like image 72
jhauberg Avatar answered Oct 01 '22 04:10

jhauberg


For ARC:

Inspired by this answer: object_getIvar fails to read the value of BOOL iVar. You have to cast function call for object_getIvar to get basic-type ivars.

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

I have made a small useful macro for fast definition of such function pointers:

#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;

Then, for basic types you need to specify calls to macro (params e.g. (long long, LongLong) will fit):

GET_IVAR_OF_TYPE_DEFININTION(int, Int)

And after that a function for receiving int(or specified) variable type become available:

int result = XYIntGetVariableFunction(object, variableName)
like image 28
BZ_M97 Avatar answered Oct 01 '22 04:10

BZ_M97