Monday, May 6, 2013

NSBlockOperation addExecutionBlock example ios


addExecutionBlock:

Adds the specified block to the receiver’s list of blocks to perform.
- (void)addExecutionBlock:(void (^)(void))block
Parameters
block
The block to add to the receiver’s list. The block should take no parameters and have no return value.
Discussion of [NSBlockOperation addExecutionBlock]
The specified block should not make any assumptions about its execution environment.
Calling this method while the receiver is executing or has already finished causes anNSInvalidArgumentException exception to be thrown.
Example of [NSBlockOperation addExecutionBlock]
NSBlockOperation *operation = [[NSBlockOperation alloc] init];
__weak NSBlockOperation *weakOperation = operation;
[operation addExecutionBlock:^{
   while( ! [weakOperation isCancelled]){
      //do something...
   }
}];
Example of [NSBlockOperation addExecutionBlock]
NSOperationQueue *operationQueue = [[NSOperationQueue alloc] init];
[operationQueue setMaxConcurrentOperationCount: 1];

NSBlockOperation *operation = [[NSBlockOperation alloc] init];
__weak NSBlockOperation *weakOperation = operation;
[operation addExecutionBlock: ^ {
    for (unsigned i=0; i < 10000000; i++) {
        if ([weakOperation isCancelled]) return;
        printf("%i\n",i);
    }
}];
[operationQueue addOperation:operation];

sleep(1);

if ([operationQueue operationCount] > 0) {
    [operationQueue cancelAllOperations];
}