Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I list all fields of an object in Objective-C?

If I have a class, how can I list all its instance variable names?

eg:

@interface MyClass : NSObject {
    int myInt;
    NSString* myString;
    NSMutableArray* myArray;
}

I would like to get "myInt", "myString", and "myArray". Is there some way to perhaps get an array of names that I can iterate over?

I've tried searching the Objective-C documentation but couldn't find anything (and I'm not sure what this is called either).


2 Answers

As mentioned, you can use the Objective-C runtime API to retrieve the instance variable names:

unsigned int varCount;

Ivar *vars = class_copyIvarList([MyClass class], &varCount);

for (int i = 0; i < varCount; i++) {
    Ivar var = vars[i];

    const char* name = ivar_getName(var);
    const char* typeEncoding = ivar_getTypeEncoding(var);

    // do what you wish with the name and type here
}

free(vars);
like image 110
jhauberg Avatar answered Sep 13 '25 09:09

jhauberg


#import <objc/runtime.h>


NSUInteger count;
Ivar *vars = class_copyIvarList([self class], &count);
for (NSUInteger i=0; i<count; i++) {
    Ivar var = vars[i];
    NSLog(@"%s %s", ivar_getName(var), ivar_getTypeEncoding(var));
}
free(vars);
like image 39
Abhishek Bedi Avatar answered Sep 13 '25 08:09

Abhishek Bedi