The following code snippet uses GCD to compute a set of integers and store them in an array.
factArray = {1!, 2!, ... n!} where k! designates factorial(k)=k*(k-1)*...*2*1.
I wonder why I can add objects to the factArray variable (instance of NSMutableArray) inside the block though factArray isn't declared with the __block qualifier.
NSUInteger n = 10;
NSMutableArray *factArray = [[NSMutableArray alloc] initWithCapacity:n];
__block NSUInteger temp = 1;
dispatch_apply(n,
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0),
^(size_t s) {
NSUInteger w;
temp *= floor(s) + 1;
w = temp;
[factArray addObject:@(w)];
});
__block NSArray *sortedArray;
double delayInSeconds = 0.1;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
sortedArray = [factArray sortedArrayUsingComparator:^NSComparisonResult(NSNumber *n1, NSNumber *n2) {
return [n1 compare:n2];
}];
NSLog(@"%@", sortedArray);
});
Of course, this code still works if we add the __block qualifier.
factArray, so... (yes, this is exactly why closures are called closures.)