我正在通过 KVO 观察一个 NSDictionary,我在其中存储我的用户偏好。
更改首选项字典时,我想将类的属性更新为新值。
我有许多子类,每个子类都有不同的属性。我正在寻找一种在超类中拥有一个方法的方法,该方法可以正确地为任何子类的各种属性将 NSDictionary 中的值分配给属性。
//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?
}
}
我知道我可以将方法子类化,并让每个子类使用自定义方法处理其特定属性。我正在寻找一种让超类处理所有子类的方法。
显然这里有很多情况......如果字典有一个键并且该属性在类中不存在,等等。让我们暂时忽略它。
有什么想法吗?