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 Cache本地缓存示例代码

《使用SpringCache本地缓存示例代码》缓存是提高应用程序性能的重要手段,通过将频繁访问的数据存储在内存中,可以减少数据库访问次数,从而加速数据读取,:本文主要介绍使用SpringCac... 目录一、Spring Cache简介核心特点:二、基础配置1. 添加依赖2. 启用缓存3. 缓存配置方案方案

使用Python的requests库来发送HTTP请求的操作指南

《使用Python的requests库来发送HTTP请求的操作指南》使用Python的requests库发送HTTP请求是非常简单和直观的,requests库提供了丰富的API,可以发送各种类型的HT... 目录前言1. 安装 requests 库2. 发送 GET 请求3. 发送 POST 请求4. 发送

Nginx中配置使用非默认80端口进行服务的完整指南

《Nginx中配置使用非默认80端口进行服务的完整指南》在实际生产环境中,我们经常需要将Nginx配置在其他端口上运行,本文将详细介绍如何在Nginx中配置使用非默认端口进行服务,希望对大家有所帮助... 目录一、为什么需要使用非默认端口二、配置Nginx使用非默认端口的基本方法2.1 修改listen指令

Python WebSockets 库从基础到实战使用举例

《PythonWebSockets库从基础到实战使用举例》WebSocket是一种全双工、持久化的网络通信协议,适用于需要低延迟的应用,如实时聊天、股票行情推送、在线协作、多人游戏等,本文给大家介... 目录1. 引言2. 为什么使用 WebSocket?3. 安装 WebSockets 库4. 使用 We

python中的显式声明类型参数使用方式

《python中的显式声明类型参数使用方式》文章探讨了Python3.10+版本中类型注解的使用,指出FastAPI官方示例强调显式声明参数类型,通过|操作符替代Union/Optional,可提升代... 目录背景python函数显式声明的类型汇总基本类型集合类型Optional and Union(py

Java使用正则提取字符串中的内容的详细步骤

《Java使用正则提取字符串中的内容的详细步骤》:本文主要介绍Java中使用正则表达式提取字符串内容的方法,通过Pattern和Matcher类实现,涵盖编译正则、查找匹配、分组捕获、数字与邮箱提... 目录1. 基础流程2. 关键方法说明3. 常见场景示例场景1:提取所有数字场景2:提取邮箱地址4. 高级

使用SpringBoot+InfluxDB实现高效数据存储与查询

《使用SpringBoot+InfluxDB实现高效数据存储与查询》InfluxDB是一个开源的时间序列数据库,特别适合处理带有时间戳的监控数据、指标数据等,下面详细介绍如何在SpringBoot项目... 目录1、项目介绍2、 InfluxDB 介绍3、Spring Boot 配置 InfluxDB4、I

使用Java读取本地文件并转换为MultipartFile对象的方法

《使用Java读取本地文件并转换为MultipartFile对象的方法》在许多JavaWeb应用中,我们经常会遇到将本地文件上传至服务器或其他系统的需求,在这种场景下,MultipartFile对象非... 目录1. 基本需求2. 自定义 MultipartFile 类3. 实现代码4. 代码解析5. 自定

使用Python实现无损放大图片功能

《使用Python实现无损放大图片功能》本文介绍了如何使用Python的Pillow库进行无损图片放大,区分了JPEG和PNG格式在放大过程中的特点,并给出了示例代码,JPEG格式可能受压缩影响,需先... 目录一、什么是无损放大?二、实现方法步骤1:读取图片步骤2:无损放大图片步骤3:保存图片三、示php

使用Python实现一个简易计算器的新手指南

《使用Python实现一个简易计算器的新手指南》计算器是编程入门的经典项目,它涵盖了变量、输入输出、条件判断等核心编程概念,通过这个小项目,可以快速掌握Python的基础语法,并为后续更复杂的项目打下... 目录准备工作基础概念解析分步实现计算器第一步:获取用户输入第二步:实现基本运算第三步:显示计算结果进