2014-01-24 21 views
-1

我有一個UISwitches的NSArray。我分別有一個NSDictionary,其鍵是NSNumbers,其對象是NSString對象形式的BOOL值。我想要做的是遍歷UISwitches的NSArray,檢查標記值是否是NSDictionary中的鍵之一,如果找到匹配項,則將UISwitch的enabled屬性設置爲鍵的對應對象(在將它從NSString轉換爲BOOL之後)。嘗試通過檢查iOS中的NSDictionary的鍵和對象來遍歷數組

我的代碼如下:

for (int i=0; i<[self.switchCollection count]; i++) { 
    UISwitch *mySwitch = (UISwitch *)[self.switchCollection objectAtIndex:i]; 
    if (tireSwitch.tag == //this has to match the key at index i) { 
        BOOL enabledValue = [[self.myDictionary objectForKey:[NSNumber numberWithInt://this is the key that is pulled from the line above]] boolValue]; 
        mySwitch.enabled = enabledValue; 
    } 
} 
+3

您遇到的問題是什麼? –

+0

我不知道如何從我的for循環中對應於索引i的字典中獲取密鑰。 – syedfa

+0

咦?你的代碼已經做到了:'[self.myDictionary objectForKey:[NSNumber numberWithInt:i]]' –

回答

1

您的代碼看起來不正確的。這個怎麼樣:

(編輯使用快速列舉(for ... in循環語法)

//Loop through the array of switches. 
for (UISwitch *mySwitch in self.switchCollection) 
{ 
    //Get the tag for this switch 
    int tag = mySwitch.tag; 

    //Try to fetch a string from the dictionary using the tag as a key 
    NSNumber *key = @(tag); 
    NSString *dictionaryValue = self.myDictionary[key]; 

    //If there is an entry in the dictionary for this tag, set the switch value. 
    if (dictionaryValue != nil) 
    { 
    BOOL enabledValue = [dictionaryValue boolValue]; 
    mySwitch.enabled = enabledValue; 
    } 
} 

這是假設我明白你想要做什麼......

+0

感謝Duncan C和Josh。我對你的知識感到謙卑。 – syedfa

2

現在, Duncan C的回答已經明確了你想要完成什麼,它可以寫得更簡單。

直接迭代陣列。根本不需要i,因爲你沒有使用它來訪問任何東西除了陣列之外。

對於每個交換機,嘗試使用tag從字典中獲取值(該值使用@()裝箱語法包裝在NSNumber中。

如果存在值,則設置交換機的enabled

for(UISwitch * switch in self.switchCollection){ 
    NSString * enabledVal = self.myDictionary[@(switch.tag)]; 
    if(enabledVal){ 
     switch.enabled = [enabledVal boolValue]; 
    } 
} 
+0

哇!這真太了不起了! – syedfa

+1

喬希,雖然你的代碼更加緊湊,但我認爲從教學角度來看,最好在論壇帖子中冗長。 –

+1

我寧願用英文來描述慣用代碼的作用@DuncanC,以便理解和良好實踐的目標都得到滿足。幸運的是,我們都可以擁有自己的方式!我的回答並不是對你的批評。 :) –