2012-11-28 28 views
1

我目前正在一個項目中,用戶在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來獲取參數的類,但它並沒有幫助。

沒有人能做到這樣的事情?

+2

'setValuesForKeysWithDictionary:'! –

+0

哦!我錯過了那一個! 非常感謝! –

回答

0

對於你必須把它們放到一個對象非對象參數,例如NSNumberNSValue。然後,您可以添加這些物體到你的字典中。

例如:

float f = 0.5; 
NSNumber f_obj = [NSNumber numberWithFloat:f]; 
3

傑克勞倫斯的評論是現貨。 你在找什麼叫做Key Value Coding,或者只是KVC。 Cocoa的這個基本部分可以讓你獲取和設置任何實例變量,使用它的名字作爲一個字符串和一個新的值。

它會自動處理將對象強制轉換爲原始值,因此您也可以將它用於int和float屬性。

還支持驗證值和處理未知屬性。

see the docs

你的代碼,而無需驗證,可以寫成

for(id eachKey in props) { 
    [anOb setValue:props[eachKey] forKey:eachKey]; 
} 

或只是

[anOb setValuesForKeysWithDictionary:props]; 

傑克說。

+0

是的,我正在做的是我保持我的驗證循環(因爲該詞典包含了我不想分析的其他信息),並且在我有TODO評論的行中創建另一個詞典。然後,我使用setValuesForKeysWithDictionary 這個新的詞典作品就像一個魅力! –