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

下面给出一个例子:

- (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在另一个线程中执行完毕后继续执行。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Objective-C是一门面向对象的编程语言,它是C语言的扩展,常用于开发iOS和Mac应用程序。在Objective-C中,线程是用来执行并发任务的执行单元。 Objective-C中处理线程的方式有多种,最常用的方式是使用NSThread类或GCD(Grand Central Dispatch)。下面我将简单介绍这两种方式: 1. NSThreadNSThreadObjective-C封装的线程类,可以手动创建和管理线程。你可以通过创建NSThread对象,并调用start方法来启动线程。NSThread提供了一些方法,如sleep、exit、cancel等,用于线程的控制和管理。 示例代码: ``` NSThread *myThread = [[NSThread alloc] initWithTarget:self selector:@selector(myThreadMethod) object:nil]; [myThread start]; ``` 2. GCD(Grand Central Dispatch):GCD是一种更现代化的多线程编程方式,它提供了一种高效且易于使用的并发模型。GCD使用队列(dispatch queue)来管理任务的执行,分为串行队列和并发队列两种类型。 示例代码: ``` // 创建并发队列 dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); // 在并发队列上异步执行任务 dispatch_async(concurrentQueue, ^{ // 执行任务的代码 }); ``` 以上是Objective-C中处理线程的两种常见方式,具体选择哪一种取决于你的需求和偏好。需要注意的是,在iOS开发中,为了确保UI的响应性,UI的更新必须在主线程(也称为主队列)上执行,可以使用GCD的主队列来实现。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值