0
我已经创建了NSObject的扩展,以允许从包含在PLIST或字典中的数据设置对象属性。我确实使用了setValuesForKeysWithDictionary
,但这只适用于不是keyPaths的密钥。我的扩展做同样的事情,除了允许PLIST包含关键路径和关键字。例如,detailTextLabel.text @“详细文本”作为键值对。改善setValueForKeyPath的健壮性
这很好,除了因PLIST中的拼写错误而可能导致应用程序崩溃。例如,如果属性名称存在但它是预期的不同类型(例如数字而不是字符串),它将崩溃。为了避免这些类型的错误,最好的方法是使这种方法更加健壮并采用防御性代码?
我已经在我的对象中使用了- (void) setValue:(id)value forUndefinedKey:(NSString *)key {}
来捕捉PLIST中与实际键不符的项目。
#pragma mark -
#pragma mark Extensions to NSObject
@implementation NSObject (SCLibrary)
- (void) setValuesForKeyPathsWithDictionary:(NSDictionary *) keyPathValues {
NSArray *keys;
int i, count;
id key, value;
keys = [keyPathValues allKeys];
count = [keys count];
for (i = 0; i < count; i++)
{
key = [keys objectAtIndex: i];
value = [keyPathValues objectForKey: key];
[self setValue:value forKeyPath:key];
}
}
在此先感谢,戴夫。