views:

246

answers:

1

1) object_getIvar(id object, Ivar ivar) returns an 'id' if the Ivar is an object eg. if the variabe is an NSString, presumably the id = NSString which contains the value. Is that correct? Or what do I need to do to access the value of the Ivar.

2) if the Ivar is a float/int etc. what will get returned and how do I convert it into something I can use (a float or int is fine as I can use NSNumber numberWithXXX to convert it to an object).

A: 

1) Correct. As stated by the docs:

Return Value
The value of the instance variable specified by ivar, or nil if object is nil.

2) No matter the type of the Ivar you will always get the value that the Ivar holds. You can determine the type of the Ivar by using ivar_getTypeEncoding. There's a list of the various type encodings here.

With that information at hand, you should be able to write a switch that handles each case appropriately; e.g.:

(warning: non-tested code ahead)

const char* typeEncoding = ivar_getTypeEncoding(var);

switch (typeEncoding) {
    case '@': {
        // handle class case
    } break;

    case 'i': {
        // handle int case
    } break;

    case 'f': {
        // handle float case
    } break;

    // .. and so on
}
Jacob H. Hansen
This can't possibly work reliably. How different types are returned depends on the ABI and isn't necessarily the same for all types. I seriously doubt this will work with structs on x86, for example.
Chuck