iOS block备忘录03

Block的常见几个用途

1.简化枚举

1
2
3
4
NSArray *array = ...
[array enumerateObjectsUsingBlock:^ (id obj, NSUInteger idx, BOOL *stop) {
NSLog(@"Object at index %lu is %@", idx, obj);
}];

2.简化并发任务

  • 使用于OperationQueue
1
2
3
4
5
6
7
8
9
10
11
NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
...
}];

// schedule task on main queue:
NSOperationQueue *mainQueue = [NSOperationQueue mainQueue];
[mainQueue addOperation:operation];

// schedule task on background queue:
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[queue addOperation:operation];
  • 使用于GCD
1
2
3
4
5
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

dispatch_async(queue, ^{
NSLog(@"Block for asynchronous execution");
});
坚持原创技术分享,您的支持将鼓励我继续创作!