有没有办法在Cocoa / Cocoa Touch的运行时动态确定类的ivars? [英] Is there a way to dynamically determine ivars of a class at runtime in Cocoa / Cocoa Touch?

查看:130
本文介绍了有没有办法在Cocoa / Cocoa Touch的运行时动态确定类的ivars?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么方法可以获得类的所有键值对的字典?

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

推荐答案

您必须使用 Objective- C运行时函数。这里有一些非常基本的示例代码。请注意,获取类的ivar不会获取其超类的ivar。你需要明确地这样做,但是函数都在运行时。

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];
}

这篇关于有没有办法在Cocoa / Cocoa Touch的运行时动态确定类的ivars?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆