0

I'm using this method to log the instance variables of a given class. And I have an array that contains all the classes in Apples API and I'm using that array in this method as the given class. But I keep getting a warning(the warning below) which I think is whats causing it to log nothing under the instance section in the console. I have another method almost identical to this that logs the methods of a given class that works great.

Method: NSArray *BNRInstanceVariables(Class cls) {

    const char instanceCount = 0;

    Method *instanceList = class_getInstanceVariable(cls, &instanceCount);

    NSMutableArray *instanceArray = [NSMutableArray array];

    for (int j = 0; j < instanceCount; j++) {

        Method currentMethod = instanceList[j];

        SEL methodSelector = method_getName(currentMethod);

        [instanceArray addObject:NSStringFromSelector(methodSelector)];
    }

    return instanceArray;
}

Warning: Incompatible pointer types initializing 'Method *' (aka 'struct objc_method **') with an expression of type 'Ivar' (aka 'struct objc_ivar *')

Result:

   classname = "__NSTaggedDate";
    hierarchy =         (
        NSObject,
        NSDate,
        "__NSTaggedDate"
    );
    instance =         (
    );
    methods =   

Answer to problem: I figured it out!!! Here is the updated code. Thanks to nkongara I changed the Method class_getInstanceVariable to an Ivar* class_copyIvarList and it fixed it but had another problem with my Method currentMethod line so I changed Method to Ivar and again solved but came up with another problem so last but not least I changed SEL line to a const char* ivar_getName().

NSArray *BNRInstanceVariables(Class cls) {

    unsigned int instanceCount = 0;

    Ivar* ivars = class_copyIvarList(cls, &instanceCount);

    NSMutableArray *instanceArray = [NSMutableArray array];

    for (int j = 0; j < instanceCount; j++) {

        Ivar currentMethod = ivars[j];

        const char* name = ivar_getName(currentMethod);

        [instanceArray addObject:NSStringFromSelector(name)];
    }

    return instanceArray;
}
  • possible duplicate of [How do I list all fields of an object in Objective-C?](http://stackoverflow.com/questions/1213901/how-do-i-list-all-fields-of-an-object-in-objective-c) – Martin R Feb 19 '14 at 15:01

1 Answers1

0

class_getInstanceVariable only returns the instance variable for the given name

You should use Ivar * class_copyIvarList(Class cls, unsigned int *outCount) for retrieving the instance variables of a class.

Following code prints all ivars in a class.

unsigned int count;
Ivar* ivars = class_copyIvarList(cls, &count);
for(unsigned int i = 0; i < count; ++i)
{
    NSLog(@"%@::%s", cls, ivar_getName(ivars[i]));
}
nkongara
  • 1,233
  • 8
  • 14