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.
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.
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.
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.
#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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With