2013-05-03 59 views
2

我正在使用Objective-C块,但是我在理解下面的代码执行过程中遇到了麻烦。块的执行流程是什么?

下面是代码:

NSArray *array = @[@"A", @"B", @"C", @"A", @"B", @"Z", @"G", @"are", @"Q"]; 
NSSet *filterSet = [NSSet setWithObjects: @"A", @"Z", @"Q", nil]; 

BOOL (^test)(id obj, NSUInteger idx, BOOL *stop); 

test = ^(id obj, NSUInteger idx, BOOL *stop) { 

    if (idx < 5) { 
     if ([filterSet containsObject: obj]) { 
      return YES; 
     } 
    } 
    return NO; 
}; 

NSIndexSet *indexes = [array indexesOfObjectsPassingTest:test]; 
NSLog(@"indexes: %@", indexes); 

输出:

indexes: <NSIndexSet: 0x10236f0>[number of indexes: 2 (in 2 ranges), indexes: (0 3)] 

在该方法中,[array indexesOfObjectsPassingTest:test];,所述test块是我传递的参数。

但是在上面的块中,test = ^(id obj, NSUInteger idx, BOOL *stop)参数objidxstop的值是多少?他们从哪里来?

回答

2

您的阵列中有9个项目。所以test块被执行9次。
每次,obj都将是数组中的对象。而idx将成为索引。

第一次:OBJ = @ “A” IDX = 0

第二时间:OBJ = @ “B” IDX = 1

stop是可以写入的值,如果你想早点退出。所以如果在第五次通过这个街区,你不想再这样做了。你可以做*stop=YES;

+0

将idx索引值自动调整为像idx = 0,idx = 1,并很快......。 – Prince 2013-05-03 12:32:00

+0

这是正确的。 – 2013-05-03 12:33:46

+0

谢谢,我刚刚执行,它自动采取上述格式..非常感谢你.... – Prince 2013-05-03 12:42:44