2013-05-03 60 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