Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
629 views
in Technique[技术] by (71.8m points)

objective c - Is there a way to dynamically determine ivars of a class at runtime in Cocoa / Cocoa Touch?

Is there a way to obtain something like a dictionary of all key-value pairs of a class?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You'd have to roll your own using the Objective-C Runtime functions. Here's some very basic sample code. Note that getting the ivars of a class doesn't get the ivars of its superclass. You'd need to do that explicitly, but the functions are all there in the runtime.

#import <objc/objc-runtime.h>
#include <inttypes.h>
#include <Foundation/Foundation.h>

@interface Foo : NSObject
{
    int i1;
}
@end
@implementation Foo
@end

@interface Bar : Foo
{
    NSString* s1;
}

@end
@implementation Bar
@end

int main(int argc, char** argv)
{
    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];

    unsigned int count;
    Ivar* ivars = class_copyIvarList([Bar class], &count);
    for(unsigned int i = 0; i < count; ++i)
    {
        NSLog(@"%@::%s", [Bar class], ivar_getName(ivars[i]));
    }
    free(ivars);


    [pool release];
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...