Set property values of an Objective-C class using reflection

后端 未结 2 773
遇见更好的自我
遇见更好的自我 2020-12-19 12:00

I am trying to learn reflection in Objective-C. I\'ve found some great information on how to dump the property list of a class, especially here, but I want to know if it is

相关标签:
2条回答
  • 2020-12-19 12:13

    The NSKeyValueCoding protocol, which NSObject implements (see NSKeyValueCoding.h), contains the method -setValuesForKeysWithDictionary:. This method takes exactly the kind of dictionary you describe and sets the appropriate properties (or ivars) of the reciever.

    This is absolutely reflection; the code in setValuesForKeysWithDictionary: accesses the properties by the names you give it, and will even find the appropriate ivar if no setter method exists.

    0 讨论(0)
  • 2020-12-19 12:27

    Objective C properties automatically conform to the NSKeyValueCoding protocol. You can use setValue:forKey: to set any property value by a string property name.

    NSDictionary * objectProperties = @{@"propertyName" : @"A value for property name",
                                        @"anotherPropertyName" : @"MOAR VALUE"};
    
    //Assuming class has properties propertyName and anotherPropertyName
    NSObject * object = [[NSObject alloc] init];
    
    for (NSString * propertyName in objectProperties.allKeys)
    {
        NSString * propertyValue = [objectProperties valueForKey:propertyName];
    
        [object setValue:propertyValue
                  forKey:propertyName];
    }
    
    0 讨论(0)
提交回复
热议问题