1

Is it possible to do something like the following in Objective-c?

   NSString *propertyName = NSStringFromSelector(aPerson.personName);

propertyName would have the string personName;

I would like to put this into a category of NSObject.

David
  • 14,205
  • 20
  • 97
  • 144
  • As you are still typing a lot. why not directly put `NSString *propertyName =@"personName";` – Anoop Vaidya Apr 03 '13 at 19:01
  • 4
    What exactly are you trying to do? –  Apr 03 '13 at 19:06
  • May be Obj-C runtime? if you want to get all propertynames...posting as answer and will see tomorow how many downvotes.. – Anoop Vaidya Apr 03 '13 at 19:08
  • @H2CO3 I don't want to be doing what `Annop` is suggesting where by I have to type out the property name into a string. – David Apr 03 '13 at 20:26
  • @David: Neither by obj-C runtime, nor by direct assignment. Even you want only a particular variablename from a class, then I guess there is no other way. Even Josh's link says Obj-c runtime. – Anoop Vaidya Apr 04 '13 at 03:34

1 Answers1

0

To get all the property names of a class

- (NSMutableArray *)getAllPropertyOfClass:(Class)aClass {
    NSMutableArray *mArray=[NSMutableArray new];
    unsigned int outCount;
    objc_property_t *properties = class_copyPropertyList([aClass class], &outCount);
    for(unsigned int i = 0; i < outCount; i++) {
        objc_property_t property = properties[i];
        const char *propName = property_getName(property);
        if(propName) {
            NSString *propertyName = [NSString stringWithUTF8String:propName];
                mArray[mArray.count]=propertyName;
        }
    }
    free(properties);
    return mArray;
}
Anoop Vaidya
  • 46,283
  • 15
  • 111
  • 140
  • I've seen this before and it returns a list of strings. I just want once string for the property that I am specifying. – David Apr 03 '13 at 20:28
  • @JoshCaswell: I simply copied, and edited here, without compile and checking. And i was half-sleep too :p night 1AM, but no excuse. thanks to all for not voting this down. – Anoop Vaidya Apr 04 '13 at 02:20
  • If you want just one. And you know **specifically which one**, then why not to assign the variableName in a string directly? Why to program and all to find? – Anoop Vaidya Apr 04 '13 at 03:32
  • @AnoopVaidya The whole idea is to get away from having to type out a string. Typing out a string is error prone. If I specify a property that a class does not have, the complier will complain. This is the behaviour that I'm looking for. – David Apr 04 '13 at 05:47
  • this is what you can do by obj-c runtime. you can get all the properties. but agian you say, you want only one? how will do maintain both the thing? i am not finding any idea. – Anoop Vaidya Apr 04 '13 at 05:53