目标c“对于每个” (快速枚举) - 收集评估? [英] Objective c "for each" (fast enumeration) -- evaluation of collection?
问题描述
static NSArray * a;
- (NSArray *)fcn
{
if(a == nil)
a = [NSArray arrayWithObjects:@one,@two,@ 三,无];
NSLog(@called);
返回一个;
$ b ...
([self fcn]中的NSString * s)
NSLog(@%@,s);
输出结果为:
2010-10-07 07:37:31.425 WidePhotoViewer Lite [23694:207]两张
2010-10-07 07:37:31.425 WidePhotoViewer Lite [23694:207]三张
指示[self fcn]只被调用一次。
任何人都可以确认这是指定(而不是仅仅观察)的行为?
我想要做的是这样的:
for(UIView * v in [innerView subviews]){
而不是这个:
$ $ $ $ $ $ $ $ NSArray * vs = [innerView subviews];
for(UIView * v in vs){
想法?
这种for循环称为快速枚举(查看NSFastEnumeration对象)。苹果公司的文档说,在为obj表达式,表达式产生一个符合NSFastEnumeration协议的对象,所以我想这是正确的行为:函数被调用一次,迭代器被创建一次,并在循环中使用。 p>
It seems from experimentation that the collection expression is evaluated only once. Consider this example:
static NSArray *a;
- (NSArray *)fcn
{
if (a == nil)
a = [NSArray arrayWithObjects:@"one", @"two", @"three", nil];
NSLog(@"called");
return a;
}
...
for (NSString *s in [self fcn])
NSLog(@"%@", s);
The output is:
2010-10-07 07:37:31.419 WidePhotoViewer Lite[23694:207] called
2010-10-07 07:37:31.420 WidePhotoViewer Lite[23694:207] one
2010-10-07 07:37:31.425 WidePhotoViewer Lite[23694:207] two
2010-10-07 07:37:31.425 WidePhotoViewer Lite[23694:207] three
indicating that [self fcn] is called only once.
Can anyone confirm that this is the specified (as opposed to merely observed) behavior?
What I have in mind is doing something like this:
for (UIView *v in [innerView subviews]) {
instead of this:
NSArray *vs = [innerView subviews];
for (UIView *v in vs) {
Thoughts?
This kind of for loop is called a "fast enumeration" (look at the NSFastEnumeration object). Apple's documentation says that in "for obj in expression", expression yields an object that conforms to the NSFastEnumeration protocol, so I guess that's the correct behaviour: the function is called once, an iterator is created once and used in the loop.
这篇关于目标c“对于每个” (快速枚举) - 收集评估?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!