ck_
ck_

Reputation: 3829

How to get properties via name? If I have `@"color"`, how do I get `self.color`?

I am observing via KVO an NSDictionary where I store my user preferences.

When the preferences dictionary is changed, I want to update my class's properties to the new values.

I have a number of subclasses, each with different properties. I'm looking for a way to have a single method in the superclass that can correctly, for any subclass's various properties, assign the values in the NSDictionary to the properties.

//Observe when user toggles preferences
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context 
{
    NSDictionary *prefs = [change objectForKey:NSKeyValueChangeNewKey];

    //I know I can do...
    //Subclass1
    self.isEnabled = [[prefs objectForKey:@"isEnabled"] boolValue];
    self.color = [[prefs objectForKey:@"color"];
    self.width = [[prefs objectForKey:@"width"];

    // -- or -- 

    //Subclass2
    self.isEnabled = [[prefs objectForKey:@"isEnabled"] boolValue];
    self.weight = [[prefs objectForKey:@"weight"];
    self.age = [[prefs objectForKey:@"age"];
    //...etc.

    //But I would prefer to do something like this... (Pseudocode)
    for (id key in prefs)
    {
        id value = [prefs objectForKey:key];
        [self propertyNamed:key] = value; // How can I accomplish this?
    }
}

I know I can subclass the method out, and have each subclass handle its particular properties with a custom method. I'm looking for a way for the superclass to handle all the subclasses.

Obviously there are a number of cases here... If the dictionary has a key and that property does not exist in the class, etc. Let's ignore that for now.

Any ideas for doing this?

Upvotes: 1

Views: 291

Answers (1)

bbum
bbum

Reputation: 162722

See NSKeyValueCoding.

[self setValue:... forKey:@"color"];
color = [self valueForKey:@"color"];

Upvotes: 11

Related Questions