-1

UISwitches の NSArray があります。キーが NSNumbers であり、オブジェクトが NSString オブジェクトの形式の BOOL 値である NSDictionary を別に持っています。私がやりたいのは、UISwitches の NSArray を反復処理し、タグ値が NSDictionary 内のキーの 1 つであるかどうかを確認し、一致が見つかった場合は、UISwitch の有効なプロパティをキーの対応するオブジェクトに設定することです(NSString から BOOL に変換した後)。

私のコードは次のとおりです。

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;
     }
 }
4

2 に答える 2

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];
    }
}
于 2014-01-24T20:09:19.183 に答える
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;
  }
}

それは、あなたがやろうとしていることを私が理解していることを前提としています...

于 2014-01-24T20:00:26.733 に答える