Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find all the property keys of a KVC compliant Objective-C object?

Is there a method that returns all the keys for an object conforming to the NSKeyValueCoding protocol?

Something along the lines of [object getPropertyKeys] that would return an NSArray of NSString objects. It would work for any KVC-compliant object. Does such a method exist? I haven't found anything in searching the Apple docs so far.

Thanks, G.

like image 678
armahg Avatar asked Apr 23 '09 09:04

armahg


People also ask

What is property in Objective C?

Objective-C properties offer a way to define the information that a class is intended to encapsulate. As you saw in Properties Control Access to an Object's Values, property declarations are included in the interface for a class, like this: @interface XYZPerson : NSObject.

What is key-value coding?

About Key-Value Coding. Key-value coding is a mechanism enabled by the NSKeyValueCoding informal protocol that objects adopt to provide indirect access to their properties. When an object is key-value coding compliant, its properties are addressable via string parameters through a concise, uniform messaging interface.

What is KVC in Swift?

According to Apple: Key-value coding is a mechanism for accessing an object's properties indirectly, using strings to identify properties, rather than through invocation of an accessor method or accessing them directly through instance variables.


2 Answers

#import "objc/runtime.h"  unsigned int outCount, i;  objc_property_t *properties = class_copyPropertyList([self class], &outCount); for(i = 0; i < outCount; i++) {     objc_property_t property = properties[i];     const char *propName = property_getName(property);     if(propName) {             const char *propType = getPropertyType(property);             NSString *propertyName = [NSString stringWithUTF8String:propName];             NSString *propertyType = [NSString stringWithUTF8String:propType];     } } free(properties); 
like image 184
oxigen Avatar answered Sep 20 '22 20:09

oxigen


Use class_getPropertyList. That will tell you all the @properties of the object.

It won't necessarily list every KVC-compliant property, because any method that takes no arguments and returns a value is a valid KVC-compliant getter. There's no 100%-reliable way for the runtime to know which ones behave as properties (e.g., -[NSString length]) and which ones behave as commands (e.g., -[NSFileHandle readDataToEndOfFile]).

You should be declaring your KVC-compliant properties as @properties anyway, so this shouldn't be too big of a problem.

like image 32
Peter Hosey Avatar answered Sep 16 '22 20:09

Peter Hosey