简体   繁体   English

获取有关是否在Objective-C中将属性设置为只读的信息的方法

[英]Way to get information on whether or not a property is set readonly in objective-c

I have got some properties in objective-c that are declared readonly such as: 我在Objective-C中有一些属性声明为只读,例如:

@property (nonatomic, readonly) NSString* aProperty;

And I want to get information on the properties readability to treat them differently (eg change the way how information about them is displayed in the GUI). 而且我想获取有关属性可读性的信息,以区别对待它们(例如,更改有关其信息在GUI中的显示方式)。 Thats why I need a way to ask if the property is readonly (I have got a list of property names and their objects in which they are contained). 这就是为什么我需要一种方法来询问属性是否为只读(我已经获得了属性名称及其包含的对象的列表)。 Is there a way to achieve this? 有没有办法做到这一点? - for example using the objective-c runtime. -例如使用Objective-C运行时。

    objc_property_t prop = class_getProperty([object class], [aProperty UTF8String]);
    if (!prop) {
       // doesn't exist for object
       return nil;
    }
    const char * propAttr = property_getAttributes(prop);
    NSString *propString = [NSString stringWithUTF8String:propAttr];
    NSArray *attrArray = [propString componentsSeparatedByString:@","];

attrArray will contain all the properties refer to this Apple Doc attrArray将包含所有与此Apple文档有关的属性

To make it easy & fast: 为了方便快捷:

objc_property_t prop = class_getProperty([object class], "aProperty");
const char * roAttr *property_copyAttributeValue(property, "R");
  1. I do not believe, that properties are encoded using UTF8. 我不相信这些属性是使用UTF8编码的。 ;-) But it should not make any difference. ;-)但不应有任何区别。

  2. This way, you do not have to construct many instances of NSString. 这样,您不必构造许多NSString实例。

  3. You do not have to pick-up the desired attribute. 您不必选择所需的属性。

  4. Always have a look to the headers. 总是看看标题。 It is a part of the documentation. 它是文档的一部分。 (property_copyAttribteValue() is only documentated at runtime.h.) (仅在runtime.h中记录了property_copyAttribteValue()。)

  5. Consider using object_getClass() instead of [object class]. 考虑使用object_getClass()代替[object class]。 This depends on the task, you have to solve. 这取决于任务,您必须解决。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM