Get object property name as string in Objective-C

Suppose you have a class "Foo" with the property "testProperty". The goal is to get the name of the property (not the value) as NSString. Perhaps this question is duplicated. Get the property name as a string . But the answers did not help me, because:

  • I do not need all the properties. I only need one.
  • For NSStringFromSelector(@selector(prop))- in any case, you need to enter a string.

Suppose I have a function like

- (NSString *)propertyToString:(id)propertyOfObject

In this case, I can use, for example, to sort

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:[self propertyToString:foo.testProperty] ascending:NO]; 

So finally, the code will be clean.

+4
source share
2

. , -, .

0

. :

#import <objc/runtime.h>

Class cls = [Foo class];
u_int count;
objc_property_t* props = class_copyPropertyList(cls,&count);
for(int i=0;i<count;i++){
    NSString* propname = [NSString stringWithUTF8String:property_getName(props[i])];
    if([propname hasPrefix:@"test"])
        NSLog(@"foo");
}

. , , - - , , - .

0

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


All Articles