0

I want to get a class's property from a string. For example:

    NSString * propertyStr = @"propertyStr";
    if ([class haveProperty:propertyStr]) {
        class.propertyStr = @"avalue";
    }

I don't know if i have say it clear.

Dracuuula
  • 313
  • 2
  • 15

4 Answers4

4

You want to check if your class have property called propertyStr, for that you can do :

NSString *propertyStr = @"propertyStr";
if ([class respondsToSelector:NSSelectorFromString(propertyStr)]) {
    class.propertyStr = @"avalue";
}
Anoop Vaidya
  • 46,283
  • 15
  • 111
  • 140
2

Since @property and @syn automatically create the getter and setters we can use the below code to check if any class responds to particular message (setter)

NSString *propertyStr = @"propertyStr";
if ([class respondsToSelector:NSSelectorFromString(propertyStr)]) 
{
[class setValue:@"Value" forKey:propertyStr];
}
Gyanendra Singh
  • 1,483
  • 12
  • 15
  • First thank you.And how to judge the property is NSString or int? – Dracuuula Dec 12 '13 at 07:25
  • You can check using if([class.propertyStr isKindOfClass[NSString Class]])// Then set the value accordingly otherwise else condition... – Gyanendra Singh Dec 12 '13 at 07:48
  • primitives are not subClass of NSObject, hence `isKindOfClass` will not work, will be an compiler error. [Check this answer](http://stackoverflow.com/questions/20537787/how-to-know-the-type-of-classs-property-from-string/20538879#20538879) – Anoop Vaidya Dec 13 '13 at 08:05
1

Try with respondsToSelector

Syntax

 if ([class respondsToSelector:@selector(property)])
        [[class property] setProperty:@"value"];

Example

if ([UINavigationBar respondsToSelector:@selector(appearance)])
    [[UINavigationBar appearance] setBarStyle:UIBarStyleBlackOpaque];
1

You can try this..

NSString *selName = @"yourPropertyName";
SEL selector = NSSelectorFromString(selName);

if ([className respondsToSelector:selector])
    className.selName = /* your action*/;
Mani
  • 17,549
  • 13
  • 79
  • 100