【问题标题】:Trying to iterate through an Array by checking against keys and objects of an NSDictionary in iOS [closed]尝试通过检查 iOS 中 NSDictionary 的键和对象来遍历数组 [关闭]
【发布时间】:2014-01-24 19:44:07
【问题描述】:

我有一个 NSArray 的 UISwitches。我分别有一个 NSDictionary,其键是 NSNumber,其对象是 NSString 对象形式的 BOOL 值。我想做的是遍历 UISwitches 的 NSArray,检查标签值是否是 NSDictionary 内部的键之一,如果找到匹配项,则将 UISwitch 的 enabled 属性设置为键的对应对象(在将其从 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;
     }
 }

【问题讨论】:

  • 您遇到了什么问题?
  • 我不知道如何从与我的 for 循环中的索引 i 对应的字典中获取键。
  • 嗯?您的代码已经这样做了:[self.myDictionary objectForKey:[NSNumber numberWithInt:i]]
  • 检索key对应的对象。我需要密钥本身(与索引 i 不同)。然后我需要使用我得到的密钥,然后检索正确的对象。
  • 给我们举个例子,说明字典里面有什么,数组里面有什么,以及你想要它们之间的什么“连接”

标签: ios objective-c nsdictionary fast-enumeration


【解决方案1】:

既然 Duncan C 的答案已经明确了您要完成的工作,那么可以更简单地编写它。

直接迭代数组。您根本不需要i,因为您没有使用它来访问数组以外的任何内容。

对于每个开关,尝试使用tag 从字典中获取一个值(这使用@() 装箱语法包装在NSNumber 中。

如果存在值,则设置开关的enabled

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

【讨论】:

  • 哇!这太棒了!
  • Josh,虽然您的代码更紧凑,但从教学的角度来看,我认为最好在论坛帖子中冗长。
  • 我宁愿用英语描述惯用代码的作用,@DuncanC,以便同时实现理解和良好实践的目标。幸运的是,我们都可以拥有自己的方式!我的回答并不是要批评你的。 :)
  • @JoshCaswell,确实如此。我们都想帮忙。 (+1)
  • 恐怕没有真正的“高级 ObjC 书籍”,@syedfa。你只需要这样做。但是,周围有一些“食谱”书籍,其中一本称为(IIRC)“可可设计模式”。 Big Nerd Ranch 有一本“高级 OS X 编程”一书(他们的所有东西都很棒),但它是关于系统功能的,而不是 ObjC。
【解决方案2】:

您的代码看起来不正确。这个怎么样:

(编辑为使用快速枚举(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;
  }
}

假设我明白你想要做什么......

【讨论】:

  • 感谢 Duncan C 和 Josh。我对你的知识感到谦卑。
猜你喜欢
  • 2021-12-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多