简体   繁体   中英

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:

@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). 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.

    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

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. ;-) But it should not make any difference.

  2. This way, you do not have to construct many instances of 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.)

  5. Consider using object_getClass() instead of [object class]. This depends on the task, you have to solve.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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