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

后端 未结 3 1984
说谎
说谎 2020-12-03 02:47

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

eg:

@interface MyClass : NSObject {
    int myInt;
    NSString* myString;
    NSM         


        
相关标签:
3条回答
  • 2020-12-03 03:30

    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);
    
    0 讨论(0)
  • 2020-12-03 03:49

    Consider gen_bridge_metadata, which is intended for a completely different purpose, but can produce XML files from Objective-C header files.

    0 讨论(0)
  • 2020-12-03 03:53
    #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);
    
    0 讨论(0)
提交回复
热议问题