views:

622

answers:

2

Can someone post an example of how I get an instance variable value that is a double? I tried using the object_getIvar() function but that didn't go very well because it seems like this function is only good for variables that return objects and not scalar data type.

thanks in advance,

fbr

+4  A: 

If you already know the name of the instance variable, you can just use KVC. Say the ivar with double value of an object x is called "weight", you do NSNumber* x=[obj valueForKey:@"weight"]; then you can get the double value by [x doubleValue]. Similarly, you can set an NSNumber num containing a double value by [obj setValue:num forKey:@"weight"].

object_getIvar() is something lower-level, useful to get the class layout and/or getting the type information of an ivar which you only know the name, etc. If KVC isn't sufficient for you, could you explain in more detail exactly what you want to achieve?

Yuji
that was very helpful! Thanks! KVC worked just fine.
ForeignerBR
A: 

While I totally agree with Yuji, and KVC is the correct approach for the vast majority of problems this question probably relates too, in the interest of the small number of cases where you really do want to go poking around in the ivars, the answer is to use object_getInstanceVariable() for this. For example:

#import <Foundation/Foundation.h>
#import <objc/runtime.h>

@interface MyObject : NSObject {
    double _someDouble;
}
@property double someDouble;
@end
@implementation MyObject
@synthesize someDouble=_someDouble;
@end

int main (int argc, const char * argv[]) {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    MyObject *object = [[MyObject alloc] init];
    object.someDouble = 3.14;
    double doubleOut;
    object_getInstanceVariable(object, "_someDouble", (void**)&doubleOut);
    NSLog(@"%f", doubleOut);
    [object release];
    [pool drain];
    return 0;
}

Note the bizarre cast of double* to a void**. It is correct, required to avoid warnings, and is a side effect of the usual use case where this returns an object pointer.

But you really shouldn't be poking around in the ivars in all but a very few cases.

Rob Napier