UI(三十二)多线程-NSOperation

什么是NSOperation

 是NSTheard 之外的另一种多线程方法

 采用NSOperation(线程操作,通常用他的子类)和NSOperationQueue(线程队列)搭配来做多线程开发,采用NSOperation指定一个操作,把这个操作放到线程队列(线程池)中,让线程队列安排他的生命周期。


 1. NSInvocationOperation与NSOperationQueue搭配使用


 2. NSBlockOperation与NSOperationQueue搭配使用,方式一和方式二没有什么本质区别,主要是后者使用block形式进行代码组织,使用相对方便


 3. 继承于NSOperation的子类与NSOperationQueue搭配使用,更方便封装某一个线程操作。


 1. 该子类需重写main方法,在main方法内做线程操作,该线程被执行就会自动调用main方法


 2. 在main方法内切记要新建一个自动释放池,因为如果是同步操作,该方法能够自动访问到主线程的自动释放池,如果是异步执行操作,那么将无法访问到主线程的自动释放池。


 3、与NSThread 有什么区别

 1、NSThread需要启动,也就是说 需要费心管理线程的生命周期,而采用NSOperation 方式只需要将线程放到线程队列中即可,线程队列负责管理、执行所有的线程操作

 2、管理线程的最大并发数,也就是同时执行的任务数

 3、控制线程之间的依赖关系,NSOperation 之间可以设置依赖来保证执行顺序。比如一定要让操作1执行完这后,才能执行操作2,线程之间不能相互依赖,不能A依赖B、B又依赖A

 4、队列的取消、暂停、恢复


#pragma makr ==NSInvocationOperation和NSOperationQueue搭配运行多线程开发===


 1、创建视图

 2、创建线程

 3、创建线程队列

 4、把线程放在线程队列中

 5、在子线程加载网络资源

// 1、创建视图

     imageView = [[UIImageView alloc]initWithFrame:CGRectMake(50, 50, 200, 200)];


    [self.view addSubview:imageView];


//  2、创建线程

 NSInvocationOperation * invocationOperation = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(loadResource) object:nil];


//3、创建线程队列

 NSOperationQueue *operationQueue = [NSOperationQueue new];//new类似alloc init


// 4、把线程放在线程队列中

[operationQueue addOperation:invocationOperation];



}

//   5、在子线程加载网络资源

-(void)loadResource{


 NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:kurl]];

 UIImage *image = [UIImage imageWithData:data];


//6、回到主线程

  [[NSOperationQueue mainQueue]addOperationWithBlock:^{

 //7、更新UI

 imageView.image = image;

  }];

#pragma mark---2. NSBlockOperation与NSOperationQueue搭配使用

 //  1、创建视图

 imageView = [[UIImageView alloc]initWithFrame:CGRectMake(50, 50, 200, 200)];


        [self.view addSubview:imageView];

 //2、创建一个线程操作

 NSBlockOperation *blockOperation = [NSBlockOperation blockOperationWithBlock:^{

//5、加载网络资源

 NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:kurl]];

 UIImage *image = [UIImage imageWithData:data];

 //6、回到主线程

        [[NSOperationQueue mainQueue]addOperationWithBlock:^{

 //7、更新UI

 imageView.image = image;

        }];

    }];


 //3、创建线程队列

 NSOperationQueue*operationQueue = [NSOperationQueue new];

//4、把线程操作放到线程队列里面

[operationQueue addOperation:blockOperation];


#pragma mark 用自定义与NSOperation 的类与NSOperationQueue搭配

// 1、创建视图

   imageView = [[UIImageView alloc]initWithFrame:CGRectMake(50, 50, 200, 200)];


  [self.view addSubview:imageView];

 //2、创建一个线程操作 在类中重写main,在main指定要进行的操作

 CustomOperation *customOperation = [[CustomOperationalloc]initWithImageView:imageView];

 //3、创建一个线程队列

 NSOperationQueue *operationQueue = [NSOperationQueue new];


//4、将线程操作放到线程队列中

[operationQueue addOperation:customOperation];

你可能感兴趣的:(UI(三十二)多线程-NSOperation)