getting ivar of fundamental types with object_getInstanceValue
getting ivar of fundamental types with object_getInstanceValue
- Subject: getting ivar of fundamental types with object_getInstanceValue
- From: Ignacio Enriquez <email@hidden>
- Date: Tue, 05 Mar 2013 11:23:45 +0900
Hello,
I am trying to understand the correct usage and caveats, of
object_setInstanceValue function from objc/objc-runtime.h.
Recently I found this code:
object_setInstanceVariable(foo, "_isRevealed", (void*)YES);
where foo is:
@interface Foo : NSObject{
double _doubled;
NSObject *obj;
BOOL _booled;
BOOL _isRevealed;
BOOL _isBar;
}
...
- (NSString *)description {
return [NSString stringWithFormat:@"%p %f, %@, %d %d %d", self, _doubled,
_obj, _booled, _isRevealed, _isBar];
}
@end
An old post in this list (Re: ivars and fundamental types -
http://lists.apple.com/archives/cocoa-dev/2010/Oct/msg00402.html) suggests
its brother object_getInstanceValue function should not be used for
fundamental types, only objects. "It happens to work for pointer-size
non-object values -- Greg Parker". I am trying this in the iOS simulator
and even though BOOL (size=1) and pointers (size=4) are not the same size
it seems to work.
What would be the best way to set the value of a ivar? Is there a situation
where above code could fail or have other consequences? Maybe in other
architectures? Depends on the offset of the ivar?
Maybe it works also for non-objects smaller-than a pointer? :p
It is still unclear to me, how is that object_getInstanceVariable only
works for pointer-size things.
This is what I've tried:
Foo *foo = [Foo new];
Ivar ivar;
NSLog(@"\nsize of BOOL: %ld\n int : %ld", sizeof(BOOL), sizeof(int));
ivar = object_setInstanceVariable(foo, "_isRevealed", (void*)NO);
NSLog(@"foo: %@, Ivar: %s %s %d", foo, ivar_getName(ivar),
ivar_getTypeEncoding(ivar), ivar_getOffset(ivar));
ivar = object_setInstanceVariable(foo, "_isRevealed", (void*)YES);
NSLog(@"foo: %@, Ivar: %s %s %d", foo, ivar_getName(ivar),
ivar_getTypeEncoding(ivar), ivar_getOffset(ivar));
ivar = object_setInstanceVariable(foo, "_isRevealed", (void*)NO);
NSLog(@"foo: %@, Ivar: %s %s %d", foo, ivar_getName(ivar),
ivar_getTypeEncoding(ivar), ivar_getOffset(ivar));
[foo release]
Result:
foo: 0x7628ef0 0.000000, (null), 0 0 0, Ivar: _isRevealed c 17
foo: 0x7628ef0 0.000000, (null), 0 1 0, Ivar: _isRevealed c 17
foo: 0x7628ef0 0.000000, (null), 0 0 0, Ivar: _isRevealed c 17
--
Ignacio
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden