如何在Objective-C中检测属性返回类型 [英] How to detect a property return type in Objective-C

查看:70
本文介绍了如何在Objective-C中检测属性返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在运行时在Objective-C中有一个对象,从中我仅知道KVC密钥,并且需要检测此属性的返回值类型(例如,我需要知道其是NSArray还是NSM​​utableArray),如何我这样做吗?

I have an object in objective-c at runtime, from which I only know the KVC key and I need to detect the return value type (e.g. I need to know if its an NSArray or NSMutableArray) of this property, how can I do that?

推荐答案

您正在谈论运行时属性自省,这恰好是Objective-C

You're talking about runtime property introspection, which happens to be something that Objective-C is very good at.

在您描述的情况下,我假设您有一个这样的类:

In the case you describe, I'm assuming you have a class like this:

@interface MyClass
{
    NSArray * stuff;
}
@property (retain) NSArray * stuff;
@end

使用XML进行编码的方式如下:

Which gets encoded in XML something like this:

<class>
    <name>MyClass</name>
    <key>stuff</key>
</class>

根据这些信息,您想重新创建该类,并为它指定一个合适的stuff值.

From this information, you want to recreate the class and also give it an appropriate value for stuff.

这是它的外观:

#import <objc/runtime.h>

// ...

Class objectClass;       // read from XML (equal to MyClass)
NSString * accessorKey;  // read from XML (equals @"stuff")

objc_property_t theProperty =
    class_getProperty(objectClass, accessorKey.UTF8String);

const char * propertyAttrs = property_getAttributes(theProperty);
// at this point, propertyAttrs is equal to: T@"NSArray",&,Vstuff
// thanks to Jason Coco for providing the correct string

// ... code to assign the property based on this information

Apple的文档(上面有链接)包含有关您可能希望在propertyAttrs中看到的内容的所有肮脏细节.

Apple's documentation (linked above) has all of the dirty details about what you can expect to see in propertyAttrs.

这篇关于如何在Objective-C中检测属性返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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