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];
}
}
在此先感謝,戴夫。