Why are the Objective-C runtime methods object_getInstanceVariable and object_setInstanceVariable are not available under Automatic Reference Counting and what can I do about it?
object_getInstanceVariable is buggy when the instance variable's size is larger than the development target's pointer size. How can I get around this?
Use the valueForKey: and setValue:forKey: methods instead. These allow you to read/write any instance variable of an object. For primitive-typed instance variables these methods return/take values wrapped as NSNumber or NSValue objects.
You have instance variables larger than the pointer size, maybe struct's? Here are some code fragments showing use with a struct, first let's define a struct:
typedef struct
{
int i;
float f;
char c;
} ThreePrimitives;
and a class with a (private) instance variable:
@interface StructClass : NSObject
...
@end
@implementation StructClass
{
ThreePrimitives myStruct;
}
...
@end
To set the instance variable:
ThreePrimitives a = { 42, 3.14, 'x' };
NSValue *wrapA = [NSValue value:&a withObjCType:@encode(ThreePrimitives)];
[sc setValue:wrapA forKey:@"myStruct"];
To read the instance variable:
ThreePrimitives b;
NSValue *extracted = [sc valueForKey:@"myStruct"];
[extracted getValue:&b];
HTH
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With