码迷,mamicode.com
首页 > 移动开发 > 详细

iOS NSOperation学习

时间:2017-09-11 14:14:51      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:sop   pre   .com   ios   cut   init   enc   sel   nil   

为什么要用NSOperation?为什么不用GCD

在我认为NSOperation的优点是可控制性的,可以随时断开,暂停线程

 1   NSBlockOperation *operationA = [NSBlockOperation blockOperationWithBlock:^{
 2         for (int i = 0; i<100; i++) {
 3             NSLog(@"-operation-下载图片-%@",[NSThread currentThread]);
 4         }
 5     }];
 6 
 7     operationA.completionBlock = ^{
 8         NSLog(@"--开始下载第二张图片--%@",[NSThread currentThread]);
 9     };
10 
11     NSLog(@"--现在在干嘛--%@",[NSThread currentThread]);
12 
13     NSOperationQueue *queue = [[NSOperationQueue alloc] init];
14     [queue addOperation:operationA];

 

NSOperation添加线程依赖

NSInvocationOperation *operation1 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(operationA:) object:nil];
    NSInvocationOperation *operation2 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(operationB:) object:nil];

    NSBlockOperation *operation3 = [NSBlockOperation blockOperationWithBlock:^{
        for (int i = 0; i<10; i++) {
            NSLog(@"NSBlockoperation3=--1-----%@",[NSThread currentThread]);
        }
    }];
    [operation3 addExecutionBlock:^{
        for (int i = 0; i<10; i++) {
            NSLog(@"NSBlockoperation3=--2-----%@",[NSThread currentThread]);
        }
    }];

    //添加依赖  不能相互依赖
    [operation1 addDependency:operation2];
    [operation2 addDependency:operation3];

    //创建NSOperationQueue
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    [queue addOperation:operation1];
    [queue addOperation:operation2];
    [queue addOperation:operation3];

 

iOS NSOperation学习

标签:sop   pre   .com   ios   cut   init   enc   sel   nil   

原文地址:http://www.cnblogs.com/iOSkcl/p/7504625.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!