2

I am working with Objective-C blocks, but I'm having troubles understanding the below code execution.

Here is the code :

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);

Output:

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

In this method, [array indexesOfObjectsPassingTest:test];, the test block is the parameter I passed.

But in the above block, test = ^(id obj, NSUInteger idx, BOOL *stop) what are the values of the parameters obj, idx and stop it can take? Where are they from?

4

1 回答 1

2

You have 9 items in your array. So the test block is executed 9 times.
Each time, obj will be the object from the array. And idx will be the index.

First time: obj=@"A" idx=0

Second time: obj=@"B" idx=1

etc.

stop is a value you can write to, if you wanted to exit early. So if on the 5th time through the block, you didn't want to do it anymore. you could do *stop=YES;

于 2013-05-03T11:46:11.320 回答