iOS多线程应用开发中使用NSOperation类的基本方法

2020-01-14 16:31:27王旭
易采站长站为您分析iOS多线程应用开发中使用NSOperation类的基本方法,代码基于传统的Objective-C,需要的朋友可以参考下  

一、NSOperation简介

1.简单说明

NSOperation的作⽤:配合使用NSOperation和NSOperationQueue也能实现多线程编程

NSOperation和NSOperationQueue实现多线程的具体步骤:

(1)先将需要执行的操作封装到一个NSOperation对象中

(2)然后将NSOperation对象添加到NSOperationQueue中

(3)系统会⾃动将NSOperationQueue中的NSOperation取出来

(4)将取出的NSOperation封装的操作放到⼀条新线程中执⾏

 2.NSOperation的子类

NSOperation是个抽象类,并不具备封装操作的能力,必须使⽤它的子类

使用NSOperation⼦类的方式有3种:

(1)NSInvocationOperation

(2)NSBlockOperation

(3)自定义子类继承NSOperation,实现内部相应的⽅法

二、 具体说明

1.NSInvocationOperation子类

创建对象和执行操作:

复制代码
//创建操作对象,封装要执行的任务
    //NSInvocationOperation   封装操作
    NSInvocationOperation *operation=[[NSInvocationOperation alloc]initWithTarget:self selector:@selector(test) object:nil];
    
    //执行操作
    [operation start];

 

说明:一旦执⾏操作,就会调用target的test方法

代码示例:

复制代码
//
//  YYViewController.m
//  01-NSOperation基本1
//
//  Created by 孔医己 on 14-6-25.
//  Copyright (c) 2014年 itcast. All rights reserved.
//

 

#import "YYViewController.h"

@interface YYViewController ()

@end