标签:
NSOperation是个抽象类,并不具备封装操作的能力,必须使用它的子类
// 创建队列
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
// 创建操作
NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(download) object:nil];
// operation直接调用start,是同步执行(在当前线程执行操作)
// [operation start];
// 添加操作到队列中,会自动异步执行
[queue addOperation:operation];
NSBlockOperation *op1 = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"1- %@", [NSThread currentThread]);
}];
[op1 start];
@implementation XMGOperation
- (void)main
{
NSLog(@"%s, %@", __func__,[NSThread currentThread]);
}
@end
GCD队列和NSOperationQueue对比
NSOperationQueue特点
自己创建
队列中会开启新线程
mainQueue
队列中不会开启新线程Invocation(了解)
// 1.创建队列
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
// 2.封装任务
NSInvocationOperation *op1 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(demo) object:nil];
// 3.将任务添加到队列中
[queue addOperation:op1];
// 1.创建队列
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
// 2.封装任务
NSBlockOperation *op1 = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"1 = %@", [NSThread currentThread]);
}];
// 3.将任务添加到队列中
[queue addOperation:op1];
// 1.创建队列
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
// addOperationWithBlock方法会做两件事情
// 1.根据传入的block, 创建一个NSBlockOperation对象
// 2.将内部创建好的NSBlockOperation对象, 添加到队列中
// 2.将任务添加到队列中
[queue addOperationWithBlock:^{
NSLog(@"1 = %@", [NSThread currentThread]);
}];
[queue addOperationWithBlock:^{
NSLog(@"2 = %@", [NSThread currentThread]);
}];
// 1.创建队列
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
// 2.封装任务
XMGOperation *op1 = [[XMGOperation alloc] init];
// 3.将任务添加到队列中
[queue addOperation:op1];
// 如果是YES, 代表需要暂停
// 如果是NO ,代表恢复执行
self.queue.suspended = YES;
// 内部会调用所有任务的cancel方法
[self.queue cancelAllOperations];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
// 开启子线程
[queue addOperationWithBlock:^{
// 回到主线程
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
}];
}];
objc
[operationB addDependency:operationA]; // 操作B依赖于操作A
op1.completionBlock = ^{
NSLog(@"第一张图片下载完毕");
};
op2.completionBlock = ^{
NSLog(@"第二张图片下载完毕");
};
---perform...
[self performSelectorOnMainThread:(SEL) withObject:(id) waitUnitlDone:(BOOL)];
---GCD
dispatch_async(dispatch_get_main_queue(),^{
});
---NSOperationQueue
[NSOperationQueue mainQueue] addOperationWithBlock:^{
}];
标签:
原文地址:http://www.cnblogs.com/wxdonly/p/5097502.html