cks*_*ubs 1 macos cocoa cocoa-touch objective-c ios
我通过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?
}
}
Run Code Online (Sandbox Code Playgroud)
我知道我可以将该方法子类化,并让每个子类使用自定义方法处理其特定属性.我正在寻找超类来处理所有子类的方法.
显然这里有很多案例......如果字典中有一个键,并且该类中没有该属性,等等.让我们暂时忽略它.
这样做的任何想法?
bbu*_*bum 11
请参见NSKeyValueCoding.
[self setValue:... forKey:@"color"];
color = [self valueForKey:@"color"];
Run Code Online (Sandbox Code Playgroud)