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

查看:27
本文介绍了如何检测 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天全站免登陆