On Mar 4, 2013, at 6:23 PM, Ignacio Enriquez <nach...@gmail.com> wrote:
> 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.

It doesn't work. object_setInstanceVariable() will write a 4-byte value to your 
1-byte ivar. That may set your ivar correctly, but it will also trample on 
other nearby ivars.

Example:

    foo = [Foo new];
    foo->_booled = YES;
    foo->_isRevealed = YES;
    foo->_isBar = YES;
    NSLog(@"before %@", foo);
    object_setInstanceVariable(foo, "_isRevealed", (void*)NO);
    NSLog(@"after  %@", foo);

    2013-03-04 18:32:46.832 a.out[77319:303] before 0x7ae13ff0 0.000000, 
(null), 1 1 1
    2013-03-04 18:32:46.834 a.out[77319:303] after  0x7ae13ff0 0.000000, 
(null), 1 0 0

Note that object_setInstanceVariable() incorrectly set two of your ivars to NO.


-- 
Greg Parker     gpar...@apple.com     Runtime Wrangler



_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

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:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Reply via email to