欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

iOS NSThread和NSOperation的基本使用详解

程序员文章站 2023-12-19 11:58:46
nsthread适合简单的耗时任务的执行,它有两种执行方法 - (void)oneclick{ [nsthread detachnewthreadselect...

nsthread适合简单的耗时任务的执行,它有两种执行方法

- (void)oneclick{
 [nsthread detachnewthreadselector:@selector(dosomething:) totarget:self withobject:@"oneclick"];
}
-(void)dosomething:(nsstring*) str{
 nslog(@"%@",str);
}
- (void)twoclick{
 nsthread* mythread = [[nsthread alloc] initwithtarget:self
             selector:@selector(dosomething:)
             object:@"twoclick"];
 [mythread start];
}

nsoperation适合需要复杂的线程调度的方法,然后它默认是使用主线程不会创建子线程

- (void)threeclick{
 // 1.创建nsinvocationoperation对象
 nsinvocationoperation *op = [[nsinvocationoperation alloc] initwithtarget:self selector:@selector(run) object:nil];
 // 2.调用start方法开始执行操作
 [op start];
}
- (void)run
{
 nslog(@"------%@", [nsthread currentthread]);
}
- (void)fourclick{
 nsblockoperation *op = [nsblockoperation blockoperationwithblock:^{
  // 在主线程
  nslog(@"1------%@", [nsthread currentthread]);
 }];
 // 添加额外的任务(在子线程执行)
 [op addexecutionblock:^{
  nslog(@"2------%@", [nsthread currentthread]);
 }];
 [op addexecutionblock:^{
  nslog(@"3------%@", [nsthread currentthread]);
 }];
 [op addexecutionblock:^{
  nslog(@"4------%@", [nsthread currentthread]);
 }];
 [op start];

}

以上这篇ios nsthread和nsoperation的基本使用详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

上一篇:

下一篇: