我正在尝试枚举一组对象,根据具体情况,这些对象可能是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结构。我可以将其中一个或两个集合转换为一个公共类,但如果可能的话,我想更好地了解这里发生了什么。
发布于 2012-09-04 00:32:44
objectEnumerator没有在NSFastEnumeration协议中声明,因此使用[enumerableSet objectEnumerator];将不起作用,因为您使用的类型‘is’没有定义该方法。
由于objectEnumerator被声明为NSArray和NSSet的属性(没有公共超类),因此您需要从一个知道它是一个数组/集合的变量设置枚举器。即:
NSEnumerator *e =
(test) ?
[[NSArray arrayWithObjects:@"one", @"two", @"three", nil] objectEnumerator]:
[[NSOrderedSet orderedSetWithObjects:@"one", @"two", @"three", nil] objectEnumerator];发布于 2012-09-04 00:33:15
好吧,不要紧。我刚刚找到了答案。objectEnumerator不是协议的一部分,所以尽管NSArray和NSOrderedSet都有objectEnumerator消息,但我不能这样使用它。相反,这似乎是可行的:
NSEnumerator *e =
(test) ?
[[NSArray arrayWithObjects:@"one", @"two", @"three", nil] objectEnumerator]:
[[NSOrderedSet orderedSetWithObjects:@"one", @"two", @"three", nil] objectEnumerator];发布于 2014-07-07 17:57:50
您具有符合NSFastEnumeration协议的对象,但您正在尝试对NSEnumerator使用“slow”枚举。相反,使用快速枚举:
id<NSFastEnumeration> enumerableSet =
(test) ?
[NSArray arrayWithObjects:@"one", @"two", @"three", nil] :
[NSOrderedSet orderedSetWithObjects:@"one", @"two", @"three", nil];
for (id object in enumerableSet) {
// ...
}请参阅苹果公司的Objective-C编程中的。
我建议尽可能使用快速枚举而不是NSEnumerator;快速枚举更清晰、更简洁、更快。
https://stackoverflow.com/questions/12251327
复制相似问题