How to enable getter / setter method selector using runtime mapping in Objective-C? (or vice versa)

Objective-C offers a reflection function at runtime. I am trying to find a selector / setter name for a declared property. I know a basic rule like field / setField: In any case, I think that reflection at runtime should offer a function to resolve the name for complete abstraction, but I could not find this function.

How to enable the getter / setter method a selector (not an implementation) of a declared property with runtime reflection in Objective-C (actually Apple Cocoa)

Or a return request. (method selector -> declared property)

+4
source share
2 answers

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

So, to get the getter and setter switch names for some property "furType" of 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 do not know the return request, except for repeating all the properties and finding matches. Hope this helps.

+8
source

A small update from my NSObject category. Hope this helps someone:

 +(SEL)getterForPropertyWithName:(NSString*)name { const char* propertyName = [name cStringUsingEncoding:NSASCIIStringEncoding]; objc_property_t prop = class_getProperty(self, propertyName); const char *selectorName = property_copyAttributeValue(prop, "G"); if (selectorName == NULL) { selectorName = [name cStringUsingEncoding:NSASCIIStringEncoding]; } NSString* selectorString = [NSString stringWithCString:selectorName encoding:NSASCIIStringEncoding]; return NSSelectorFromString(selectorString); } +(SEL)setterForPropertyWithName:(NSString*)name { const char* propertyName = [name cStringUsingEncoding:NSASCIIStringEncoding]; objc_property_t prop = class_getProperty(self, propertyName); char *selectorName = property_copyAttributeValue(prop, "S"); NSString* selectorString; if (selectorName == NULL) { char firstChar = (char)toupper(propertyName[0]); NSString* capitalLetter = [NSString stringWithFormat:@"%c", firstChar]; NSString* reminder = [NSString stringWithCString: propertyName+1 encoding: NSASCIIStringEncoding]; selectorString = [@[@"set", capitalLetter, reminder, @":"] componentsJoinedByString:@""]; } else { selectorString = [NSString stringWithCString:selectorName encoding:NSASCIIStringEncoding]; } return NSSelectorFromString(selectorString); } 
0
source

Source: https://habr.com/ru/post/1385716/


All Articles