我目前正在一個項目中,用戶在NSDictionnary中定義了一些參數,我正在使用它來設置一些對象。 例如,您可以要求創建一個聲音對象,其參數爲param1 = xxx,param2 = yyy,gain = 3.5 ...然後是參數爲speed = 10,active = YES,name = zzz的Enemi對象...從NSDictionnary設置ivars
{
active = NO;
looping = YES;
soundList = "FINAL_PSS_imoverhere_all";
speed = 100.0;
}
我然後實例化我的班,並且想從這個dictionnary自動設置實例變量。 我已經寫了一些代碼來檢查這個參數是否存在,但是我在設置參數值時遇到了麻煩,特別是當參數是非對象(float或bool)時。
下面是我在做什麼至今:
//aKey is the name of the ivar
for (NSString *aKey in [properties allKeys]){
//create the name of the setter function from the key (parameter -> setParameter)
NSString *setterName = [aKey stringByReplacingCharactersInRange:NSMakeRange(0,1) withString:[[aKey substringToIndex:1] uppercaseString]];
setterName = [NSString stringWithFormat:@"set%@:",setterName];
SEL setterSelector = NSSelectorFromString(setterName);
//Check if the parameter exists
if ([pge_object respondsToSelector:setterSelector]){
//TODO : automatically set the parameter
}
else{
[[PSMessagesChecker sharedInstance]logMessage:[NSString stringWithFormat:@"Cannot find %@ on %@", aKey, [dict objectForKey:@"type"]] inColor:@"red"];
NSLog(@"Cannot find %@ on %@", aKey, [dict objectForKey:@"type"]);
}
}
}
正如你所看到的,我不知道該怎麼辦,一旦我發現存在的對象上的參數。我嘗試使用「performSelector ... withObject ...,但我的問題是,一些參數是非對象(浮動或布爾) 我也嘗試通過使用setter來獲取參數的類,但它並沒有幫助。
沒有人能做到這樣的事情?
'setValuesForKeysWithDictionary:'! –
哦!我錯過了那一個! 非常感謝! –