猫猫分享,必须精品
原创文章,欢迎转载。转载请注明:翟乃玉的博客 地址:?viewmode=contents
一:简单介绍1:NSOperation的作使用步骤:
配合使用NSOperation和NSOperationQueue也能实现多线程编程。
NSOperation和NSOperationQueue实现多线程的具体步骤:
(1)先将需要执行的操作封装到一个NSOperation对象中(子类实例)。
NSOperationQueue的作用:NSOperation可以调用start方法来执行任务,但默认是同步执行的如果将NSOperation添加到NSOperationQueue(操作队列)中,系统会自动异步执行NSOperation中的操作。
(2)然后将NSOperation对象添加到NSOperationQueue中。
//这里是两个子类的方法后面详细介绍- (void)addOperation:(NSOperation *)op;- (void)addOperationWithBlock:(void (^)(void))block;
(3)系统会动将NSOperationQueue中的NSOperation取出来。
(4)将取出的NSOperation封装的操作放到条新线程中执。
2.NSOperation的子类
NSOperation是个抽象类,并不具备封装操作的能力,必须使它的子类
使用NSOperation类的方式有3种:
(1)NSInvocationOperation
(2)NSBlockOperation
(3)自定义子类继承NSOperation,实现内部相应的法
NSOperation的三种用法(子类)1:NSInvocationOperation
最简单的用法(在主线程中:)
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{// 1.创建1个操作NSInvocationOperation *operation = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(download) object:nil];// 2.开启操作[operation start];}-(void)download{NSLog(@”download—%@”, [NSThread currentThread]);}
异步的方法(记住这个)
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{// 1.创建一个队列(非主队列)NSOperationQueue *queue = [[NSOperationQueue alloc] init];// 2.创建1个操作NSInvocationOperation *operation = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(download) object:nil];// 3 .将操作添加到队列(非主队列)————这一步内部相当于开启[queue addOperation:operation];}-(void)download{NSLog(@”download—%@”, [NSThread currentThread]);}
效果:线程3(其中系统会自动给我们分配最合适的线程)
注意:操作对象默认在主线程中执行(前一个),只有添加到队列中才会开启新的线程。即默认情况下,如果操作没有放到队列中queue中,都是同步执行。只有将NSOperation放到一个NSOperationQueue中,才会异步执行操作
2:NSBlockOperation
第二种也很简单:
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{// 1.创建一个队列(非主队列)NSOperationQueue *queue = [[NSOperationQueue alloc] init];// 2.创建1个操作NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{NSLog(@”download—%@”, [NSThread currentThread]);}];// 3 .将操作添加到队列(非主队列)————这一步内部相当于开启[queue addOperation:operation];}
效果:
这里还有中写法是直接将block添加到queue中
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{// 1.创建一个队列(非主队列)NSOperationQueue *queue = [[NSOperationQueue alloc] init];// 2.将操作添加到队列(非主队列)————这一步内部相当于开启[queue addOperationWithBlock:^{NSLog(@”download—%@”, [NSThread currentThread]);}];}3:自定义子类继承NSOperation,实现内部相应的法
这个也不难,就是自定义一个NSOperation的子类,,实现他的main方法
自定义类的写法
@implementation NYOperation-(void)main{NSLog(@”download—%@”, [NSThread currentThread]);}@end
controller调用写法
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{// 1.创建一个队列(非主队列)NSOperationQueue *queue = [[NSOperationQueue alloc] init];// 2.创建1个操作NYOperation *operation = [[NYOperation alloc]init];// 3 .将操作添加到队列(非主队列)————这一步内部相当于开启[queue addOperation:operation];}
结果:
时光的消化是这样的缓慢。虽然这也仅仅是无处可说的委屈。而不是痛苦。