【问题标题】:How to enumerate an arbitrary set that conforms to NSFastEnumeration如何枚举符合 NSFastEnumeration 的任意集合
【发布时间】:2012-08-28 09:29:36
【问题描述】:

我试图枚举一堆对象,根据情况,这些对象可能是 NSArray 或 NSOrderedSet。由于两者都符合 NSFastEnumeration,我希望这可以工作:

id<NSFastEnumeration> enumerableSet =
(test) ?
[NSArray arrayWithObjects:@"one", @"two", @"three", nil] :
[NSOrderedSet orderedSetWithObjects:@"one", @"two", @"three", nil];

NSEnumerator *e = [enumerableSet objectEnumerator];

但是,我收到以下编译器错误:

选择器“objectEnumerator”没有已知的实例方法。

我怀疑这里有一些语法错误,我以前没有用过 id 构造。我可以将一组或两组转换为一个通用类,但如果可能的话,我想更好地了解这里发生了什么。

【问题讨论】:

    标签: objective-c ios nsenumerator objective-c-protocol


    【解决方案1】:

    objectEnumerator 未在NSFastEnumeration 协议中声明,因此使用[enumerableSet objectEnumerator]; 将不起作用,因为您正在使用未定义该方法的类型“id”。

    由于objectEnumerator 被声明为 NSArray 和 NSSet(没有公共超类)的属性,因此您需要从知道它是数组/集合的变量中设置枚举数。即:

    NSEnumerator *e = 
    (test) ?
    [[NSArray arrayWithObjects:@"one", @"two", @"three", nil] objectEnumerator]:
    [[NSOrderedSet orderedSetWithObjects:@"one", @"two", @"three", nil] objectEnumerator];
    

    【讨论】:

      【解决方案2】:

      好吧,没关系。我刚刚找到了我的答案。 objectEnumerator 不是协议的一部分 - 所以虽然 NSArray 和 NSOrderedSet 一个 objectEnumerator 消息,但我不能这样使用它。相反,这似乎有效:

      NSEnumerator *e =
      (test) ?
      [[NSArray arrayWithObjects:@"one", @"two", @"three", nil] objectEnumerator]:
      [[NSOrderedSet orderedSetWithObjects:@"one", @"two", @"three", nil] objectEnumerator];
      

      【讨论】:

        【解决方案3】:

        您有符合NSFastEnumeration 协议的对象,但您正尝试对NSEnumerator 使用“慢”枚举。相反,使用快速枚举:

        id<NSFastEnumeration> enumerableSet =
        (test) ?
        [NSArray arrayWithObjects:@"one", @"two", @"three", nil] :
        [NSOrderedSet orderedSetWithObjects:@"one", @"two", @"three", nil];
        
        for (id object in enumerableSet) {
            // ...
        }
        

        参见 Apple 的Objective-C 编程中的Fast Enumeration Makes It Easy to Enumerate a Collection

        我建议尽可能使用快速枚举而不是NSEnumerator;快速枚举更清晰、更简洁、更快。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-02-18
          • 2015-10-14
          • 2013-01-25
          • 2011-04-09
          • 1970-01-01
          相关资源
          最近更新 更多