Eonil Eonil - 4 months ago 15
Objective-C Question

How to resolve property getter/setter method selector using runtime reflection in Objective-C? (or reverse)

Objective-C offers runtime reflections feature. I'm trying to find getter/setter selector name of a declared property. I know the basic rule like

field
/
setField:
. Anyway I think runtime reflection should offer a feature to resolve the name for complete abstraction, but I couldn't find the function.

How can I resolve the getter/setter method selector (not implementation) of a declared property with runtime reflection in Objective-C (actually Apple's Cocoa)

Or reverse query. (method selector → declared property)

Answer

I think you can get the selector names only if the property is declared with explicit (setter = XXX and/or getter = XXX)

So to get the getter and setter selector names for some property 'furType' of the class 'Cat':

objc_property_t prop = class_getProperty([Cat class], "furType");

char *setterName = property_copyAttributeValue(prop, "S");
if (setterName == NULL) { /*Assume standard setter*/ }

char *getterName = property_copyAttributeValue(prop, "G");
if (getterName == NULL) { /*Assume standard getter */ }

I don't know of a reverse query, other than iterating through all the properties and looking for matches. Hope that helps.