Objective C关键字'in'

时间:2012-01-25 13:02:39

标签: objective-c

我在理解我继承的程序中的某些代码时遇到了一些问题。

CGPoint tapLocation = [gesture locationInView:self.view];
for (UIView *view in self.view.subviews){
    if (!CGRectContainsPoint(view.frame, tapLocation)){
        //do something
    }
}

问题是我不知道关键字'in'在做什么。我一直在搜索,只能找到一些模糊的引用和一个post here

帖子说:

in: argument is an input argument only and won’t be referenced later

我真的不明白这是如何适用于上面的代码的。任何帮助将不胜感激。

7 个答案:

答案 0 :(得分:3)

我认为苹果称之为fast enumeration

在其他语言中,“for each”-loop提供了类似的功能。

答案 1 :(得分:1)

你看到的“in”是Fast Enumeration的一部分。

Here is some documentation for it.

编辑 :Derek在下面的评论中指出了另一些文档。

答案 2 :(得分:1)

这是迭代集合的简洁方法。在哪里说:

for (object in collection)

这意味着“此代码对集合中的每个对象都会发生一次”。

答案 3 :(得分:1)

您在问题中指定的链接中的 in 完全不同 for 循环。农夫来自 @encoding ,后者出现在 for 循环的上下文中。这种 for 循环通常称为 for-each 循环,而在Objective-C中,它被称为 枚举

答案 4 :(得分:0)

它会自动为您创建一个枚举器,以便您可以对集合进行迭代。因此集合必须符合NSFastEnumeration。

答案 5 :(得分:0)

in用于遍历数组。

例如:

    NSArray *values = [NSArray arrayWithObjects:@"val1", @"val2", @"val3", nil];
    for (NSString *val in values) {
            NSLog(@"Value = '%@'", val);
    }

答案 6 :(得分:0)

基本上,这是为objective-c构建的for循环的扩展。 想想这样的代码:

for (NSArray *arr = UIViewGetSubviews(UIViewControllerGetView(self)), i = 0; i < arr.count; i++)  {
}

请注意,实际实现使用NSEnumerator,而不是for for integer variable loop。