NSThread的简单使用 及performSelectorInBackground:withObject

本文主要是介绍NSThread的简单使用 及performSelectorInBackground:withObject,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

NSThread的简单使用 及performSelectorInBackground:withObject


在ios开发过程中,经常会遇到在服务器端获取完数据通过后台使用多线程方式自动更新UI,通常的做法有两种:

1、使用NSObject类的方法performSelectorInBackground:withObject:来创建一个线程。

具体的代码:

[Object performSelectorInBackground:@selector(doSomething:) withObject:nil];

2、选择使用NSThread实现多线程。

NSThread创建主要有两种方式:

(1):

[NSThread detachNewThreadSelector:@selector(doSomething:) toTarget:self withObject:nil];

(2):

NSThread* myThread = [[NSThread alloc] initWithTarget:self   selector:@selector(doSomething:) object:nil];

[myThread start];

这两种方式的区别在于:

前一种调用就会立即创建一个线程并执行selector方法;第二种方式尽管alloc了一个新Thread,但需要手动调用start方法来启动线程。这点与Java创建线程的方式相似。

第一种方式,与上述做法1使用NSObject的类方法performSelectorInBackground:withObject:是一样的;第二种方式的可以在start真正创建线程之前对其进行设置,比如设置线程的优先级。

注意:

- (void) doSomething:(id)sender

{

    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    //执行你的代码

   [pool release];

}

在多线程的执行方法doSomething中需要自行管理内存的释放,否则可能会警告提示:

XXXXX nsthread autoreleased with no pool in place – just leaking


补充:如果要更新UI必须回到主线程中,可以用performSelectorOnMainThread回到主线程(更新UI的话必须到主线程),用或者调用或者调用 委托函数,在主线程中实现委托函数


下面的这些函数是定义在NSObject中的,关于它们的具体含义,你可以在官方文档中找,或者google之,这里就不啰嗦了。

Sending Messages

  • – performSelector:withObject:afterDelay:
  • – performSelector:withObject:afterDelay:inModes:
  • – performSelectorOnMainThread:withObject:waitUntilDone:
  • – performSelectorOnMainThread:withObject:waitUntilDone:modes:
  • – performSelector:onThread:withObject:waitUntilDone:
  • – performSelector:onThread:withObject:waitUntilDone:modes:
  • – performSelectorInBackground:withObject:
  • cancelPreviousPerformRequestsWithTarget:
  • cancelPreviousPerformRequestsWithTarget:selector:object:

下面给出一个例子:

- (IBAction)Start:(id)sender {
    [self performSelector:@selector(doSomething:)];
    //[self doSomething:nil];
    //[self per
    [self performSelectorInBackground:@selector(doSomething:) withObject:nil];
    
}

-(void)doSomething:(id)inputData
{
    if([NSThread isMainThread])
    {
        NSLog(@"in main thread");
        
    }
    else {
        NSLog(@"not in main thread");
    }
    NSLog(@"kkkkk");
}

 

返回目录

1. 对当前Run Loop中Selector Sources的取消

NSObject中的performSelector:withObject:afterDelay:方法将会在当前线程的Run Loop中根据afterDelay参数创建一个Timer,如果没有调用有inModes参数的方法,该Timer会运行在当前Run Loop的默认模式中,也就是NSDefaultRunLoopMode定义的模式中。

performSelector:withObject:afterDelay:方法的使用看起来还是很简单的。这里讲另外一个辅助函数,NSObject中静态的cancelPreviousPerformRequestsWithTarget方法。该方法就是专门用来取消取消performSelector:withObject:afterDelay:方法所创建的Selector source(内部上就是一个Run Loop的Timer source)。因此该方法和performSelector:withObject:afterDelay:方法一样,只限于当前Run Loop中。

 

我们可以利用cancelPreviousPerformRequestsWithTarget直接取消一个对象在当前Run Loop中的所有未执行的performSelector:withObject:afterDelay:方法所产生的Selector Sources,如下代码:

- (void)viewDidLoad
{
    [super viewDidLoad];

    
    [self performSelector:@selector(test:) withObject:nil afterDelay:1];
    [self performSelector:@selector(test:) withObject:@"mgen" afterDelay:2];
    [NSObject cancelPreviousPerformRequestsWithTarget:self];    
}- (void)test:(id)obj
{
    NSLog(@"调用成功: %@", obj);
}

不会有任何输出,因为两个调用都被取消了。

 

如果想取消单独一个的话,需使用cancelPreviousPerformRequestsWithTarget:selector:object:方法,注意selector和object参数需要一一对应。如下代码:

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self performSelector:@selector(test:) withObject:[NSNumber numberWithInt:26] afterDelay:1];
    [self performSelector:@selector(test:) withObject:[NSNumber numberWithInt:17] afterDelay:2];
    [self performSelector:@selector(test:) withObject:[NSNumber numberWithInt:17] afterDelay:3];
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(test:) object:[NSNumber numberWithInt:17]];    
}- (void)test:(id)obj
{
    NSLog(@"调用成功: %@", obj);
}

 

只会输出:

调用成功: 26

其他两个Selector都被取消了。

 

返回目录

2. 在NSThread中执行Selector

这个话题很简单,直接通过NSObject的performSelectorInBackground:withObject:方法就可以,如下代码:

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self threadInfo:@"UI"];
    [self performSelectorInBackground:@selector(test:) withObject:nil];

}- (void)test:(id)obj
{
    @autoreleasepool
    {
        [self threadInfo:@"test"];
    }
}
- (void)threadInfo:(NSString*)category
{
    NSLog(@"%@ - %@", category, [NSThread currentThread]);
}

 

输出:

UI - <NSThread: 0x71639e0>{name = (null), num = 1}
test - <NSThread: 0x7176ad0>{name = (null), num = 3}

 

这个方法完全等效于NSThread的detachNewThreadSelector:toTarget:withObject:静态方法,那么上面NSObject的performSelectorInBackground:withObject:方法调用完全可以替换成:

[NSThread detachNewThreadSelector:@selector(test:) toTarget:self withObject:nil];

 

当然,用户也可以自行手动创建一个NSThread来完成上述功能,代码如下:

NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(test:) object:nil];
[thread start];

这两种方法运行后的输出是和第一种类似的。

 

返回目录

3. 在NSThread中的Run Loop中执行Selector

这里需要的方法是NSObject的performSelector:onThread:withObject:waitUntilDone:方法。由于是在另一个NSThread中执行Selector,所以我们需要手动开始Run Loop。首先需要在ViewController中定义两个字段,分别是NSThread和控制线程内Run Loop执行的flag。

@interface ViewController ()
{
    NSThread *_thread;
    BOOL _isNewThreadAborted;
}

 

接下来做的是执行这个线程,并且在线程中手动调用NSRunLoop的runMode:beforeDate:方法。这里注意,如果Run Loop没有任何Source的话,该方法会立即返回,所以需要创建一个循环来持续调用Run Loop的runMode:beforeDate:方法。并在Selector执行结束后同时尝试结束这个循环。最终代码如下:

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self threadInfo:@"UI"];
    
    _isNewThreadAborted = NO;
    _thread = [[NSThread alloc] initWithTarget:self selector:@selector(newThread:) object:nil];
    //开始线程
    [_thread start];
    //在另一个线程中的Run Loop中执行Selector
    [self performSelector:@selector(test:) onThread:_thread withObject:nil waitUntilDone:NO];    
}//在新线程中创建并开始一个NSRunLoop
- (void)newThread:(id)obj
{
    @autoreleasepool
    {
        NSRunLoop *currentRunLoop = [NSRunLoop currentRunLoop];
        while (!_isNewThreadAborted)
        {
            [currentRunLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
        }
        NSLog(@"线程停止");
    }
}//Selector执行
- (void)test:(id)obj
{
    [self threadInfo:@"test"];
    _isNewThreadAborted = YES;
}- (void)threadInfo:(NSString*)category
{
    NSLog(@"%@ - %@", category, [NSThread currentThread]);
}

 

输出:

UI - <NSThread: 0x717e7e0>{name = (null), num = 1}
test - <NSThread: 0x8078a80>{name = (null), num = 3}
线程停止

最后注意performSelector:onThread:withObject:waitUntilDone:方法中最后的waitUntilDone参数,如果传YES的话,当前线程会等待Selector在另一个线程中执行完毕后继续执行。


这篇关于NSThread的简单使用 及performSelectorInBackground:withObject的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1019888

相关文章

使用Python删除Excel中的行列和单元格示例详解

《使用Python删除Excel中的行列和单元格示例详解》在处理Excel数据时,删除不需要的行、列或单元格是一项常见且必要的操作,本文将使用Python脚本实现对Excel表格的高效自动化处理,感兴... 目录开发环境准备使用 python 删除 Excphpel 表格中的行删除特定行删除空白行删除含指定

深入理解Go语言中二维切片的使用

《深入理解Go语言中二维切片的使用》本文深入讲解了Go语言中二维切片的概念与应用,用于表示矩阵、表格等二维数据结构,文中通过示例代码介绍的非常详细,需要的朋友们下面随着小编来一起学习学习吧... 目录引言二维切片的基本概念定义创建二维切片二维切片的操作访问元素修改元素遍历二维切片二维切片的动态调整追加行动态

prometheus如何使用pushgateway监控网路丢包

《prometheus如何使用pushgateway监控网路丢包》:本文主要介绍prometheus如何使用pushgateway监控网路丢包问题,具有很好的参考价值,希望对大家有所帮助,如有错误... 目录监控网路丢包脚本数据图表总结监控网路丢包脚本[root@gtcq-gt-monitor-prome

Python通用唯一标识符模块uuid使用案例详解

《Python通用唯一标识符模块uuid使用案例详解》Pythonuuid模块用于生成128位全局唯一标识符,支持UUID1-5版本,适用于分布式系统、数据库主键等场景,需注意隐私、碰撞概率及存储优... 目录简介核心功能1. UUID版本2. UUID属性3. 命名空间使用场景1. 生成唯一标识符2. 数

SpringBoot中如何使用Assert进行断言校验

《SpringBoot中如何使用Assert进行断言校验》Java提供了内置的assert机制,而Spring框架也提供了更强大的Assert工具类来帮助开发者进行参数校验和状态检查,下... 目录前言一、Java 原生assert简介1.1 使用方式1.2 示例代码1.3 优缺点分析二、Spring Fr

Android kotlin中 Channel 和 Flow 的区别和选择使用场景分析

《Androidkotlin中Channel和Flow的区别和选择使用场景分析》Kotlin协程中,Flow是冷数据流,按需触发,适合响应式数据处理;Channel是热数据流,持续发送,支持... 目录一、基本概念界定FlowChannel二、核心特性对比数据生产触发条件生产与消费的关系背压处理机制生命周期

java使用protobuf-maven-plugin的插件编译proto文件详解

《java使用protobuf-maven-plugin的插件编译proto文件详解》:本文主要介绍java使用protobuf-maven-plugin的插件编译proto文件,具有很好的参考价... 目录protobuf文件作为数据传输和存储的协议主要介绍在Java使用maven编译proto文件的插件

SpringBoot线程池配置使用示例详解

《SpringBoot线程池配置使用示例详解》SpringBoot集成@Async注解,支持线程池参数配置(核心数、队列容量、拒绝策略等)及生命周期管理,结合监控与任务装饰器,提升异步处理效率与系统... 目录一、核心特性二、添加依赖三、参数详解四、配置线程池五、应用实践代码说明拒绝策略(Rejected

C++ Log4cpp跨平台日志库的使用小结

《C++Log4cpp跨平台日志库的使用小结》Log4cpp是c++类库,本文详细介绍了C++日志库log4cpp的使用方法,及设置日志输出格式和优先级,具有一定的参考价值,感兴趣的可以了解一下... 目录一、介绍1. log4cpp的日志方式2.设置日志输出的格式3. 设置日志的输出优先级二、Window

Ubuntu如何分配​​未使用的空间

《Ubuntu如何分配​​未使用的空间》Ubuntu磁盘空间不足,实际未分配空间8.2G因LVM卷组名称格式差异(双破折号误写)导致无法扩展,确认正确卷组名后,使用lvextend和resize2fs... 目录1:原因2:操作3:报错5:解决问题:确认卷组名称​6:再次操作7:验证扩展是否成功8:问题已解