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

相关文章

Spring IoC 容器的使用详解(最新整理)

《SpringIoC容器的使用详解(最新整理)》文章介绍了Spring框架中的应用分层思想与IoC容器原理,通过分层解耦业务逻辑、数据访问等模块,IoC容器利用@Component注解管理Bean... 目录1. 应用分层2. IoC 的介绍3. IoC 容器的使用3.1. bean 的存储3.2. 方法注

Python内置函数之classmethod函数使用详解

《Python内置函数之classmethod函数使用详解》:本文主要介绍Python内置函数之classmethod函数使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地... 目录1. 类方法定义与基本语法2. 类方法 vs 实例方法 vs 静态方法3. 核心特性与用法(1编程客

Linux中压缩、网络传输与系统监控工具的使用完整指南

《Linux中压缩、网络传输与系统监控工具的使用完整指南》在Linux系统管理中,压缩与传输工具是数据备份和远程协作的桥梁,而系统监控工具则是保障服务器稳定运行的眼睛,下面小编就来和大家详细介绍一下它... 目录引言一、压缩与解压:数据存储与传输的优化核心1. zip/unzip:通用压缩格式的便捷操作2.

使用Python实现可恢复式多线程下载器

《使用Python实现可恢复式多线程下载器》在数字时代,大文件下载已成为日常操作,本文将手把手教你用Python打造专业级下载器,实现断点续传,多线程加速,速度限制等功能,感兴趣的小伙伴可以了解下... 目录一、智能续传:从崩溃边缘抢救进度二、多线程加速:榨干网络带宽三、速度控制:做网络的好邻居四、终端交互

Python中注释使用方法举例详解

《Python中注释使用方法举例详解》在Python编程语言中注释是必不可少的一部分,它有助于提高代码的可读性和维护性,:本文主要介绍Python中注释使用方法的相关资料,需要的朋友可以参考下... 目录一、前言二、什么是注释?示例:三、单行注释语法:以 China编程# 开头,后面的内容为注释内容示例:示例:四

Go语言数据库编程GORM 的基本使用详解

《Go语言数据库编程GORM的基本使用详解》GORM是Go语言流行的ORM框架,封装database/sql,支持自动迁移、关联、事务等,提供CRUD、条件查询、钩子函数、日志等功能,简化数据库操作... 目录一、安装与初始化1. 安装 GORM 及数据库驱动2. 建立数据库连接二、定义模型结构体三、自动迁

ModelMapper基本使用和常见场景示例详解

《ModelMapper基本使用和常见场景示例详解》ModelMapper是Java对象映射库,支持自动映射、自定义规则、集合转换及高级配置(如匹配策略、转换器),可集成SpringBoot,减少样板... 目录1. 添加依赖2. 基本用法示例:简单对象映射3. 自定义映射规则4. 集合映射5. 高级配置匹

Spring 框架之Springfox使用详解

《Spring框架之Springfox使用详解》Springfox是Spring框架的API文档工具,集成Swagger规范,自动生成文档并支持多语言/版本,模块化设计便于扩展,但存在版本兼容性、性... 目录核心功能工作原理模块化设计使用示例注意事项优缺点优点缺点总结适用场景建议总结Springfox 是

嵌入式数据库SQLite 3配置使用讲解

《嵌入式数据库SQLite3配置使用讲解》本文强调嵌入式项目中SQLite3数据库的重要性,因其零配置、轻量级、跨平台及事务处理特性,可保障数据溯源与责任明确,详细讲解安装配置、基础语法及SQLit... 目录0、惨痛教训1、SQLite3环境配置(1)、下载安装SQLite库(2)、解压下载的文件(3)、

使用Python绘制3D堆叠条形图全解析

《使用Python绘制3D堆叠条形图全解析》在数据可视化的工具箱里,3D图表总能带来眼前一亮的效果,本文就来和大家聊聊如何使用Python实现绘制3D堆叠条形图,感兴趣的小伙伴可以了解下... 目录为什么选择 3D 堆叠条形图代码实现:从数据到 3D 世界的搭建核心代码逐行解析细节优化应用场景:3D 堆叠图