zoukankan      html  css  js  c++  java
  • iOS: 常驻线程

    如何开启

    首先开启一个线程:

     1 @property (nonatomic, strong) NSThread *thread;
     2 
     3 - (IBAction)startAction:(id)sender {
     4     NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(start) object:nil];
     5     thread.name = @"com.live.thread";
     6     // 开启子线程
     7     [thread start];
     8     self.thread = thread;
     9 }
    10 
    11 - (void)start {
    12     NSLog(@"start----%@",[NSThread currentThread]);
    13 }
    14 
    15 - (IBAction)taskAction:(id)sender {
    16     /*
    17      如果设置wait为YES:等待当前线程执行完以后,主线程才会执行aSelector方法;
    18      设置为NO:不等待当前线程执行完,就在主线程上执行aSelector方法。
    19      如果,当前线程就是主线程,那么aSelector方法会马上执行。
    20      */
    21     [self performSelector:@selector(task) onThread:self.thread withObject:nil waitUntilDone:YES];
    22     
    23 }
    24 
    25 - (void)task {
    26     NSLog(@"task----%@",[NSThread currentThread]);
    27 }

    根据代码可知,执行startAction,打印

    start----<NSThread: 0x280b84c40>{number = 6, name = com.live.thread}

    我们知道一个线程执行完任务后就会自动销毁,再次调用此线程去执行任务即会报错:

    所以我们一般启动Runloop来使线程常驻,修改代码如下:

    1 - (void)start {
    2     NSLog(@"start----%@",[NSThread currentThread]);
    3     @autoreleasepool {
    4         do {
    5             [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:1]];
    6         } while (YES);
    7     }
    8 }

    便可成功执行task:

    start----<NSThread: 0x2807d5300>{number = 7, name = com.live.thread}

    task----<NSThread: 0x2807d5300>{number = 7, name = com.live.thread}

    如何停止

    代码如下:

     1 @property (nonatomic, assign) BOOL cancelled;
     2 
     3 - (IBAction)stopAction:(id)sender {
     4     [self performSelector:@selector(stop) onThread:self.thread withObject:nil waitUntilDone:NO];
     5 
     6     NSLog(@"退出runLoop");
     7 }
     8 
     9 - (void)start {
    10     NSLog(@"start----%@",[NSThread currentThread]);
    11     @autoreleasepool {
    12         do {
    13             [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:1]];
    14         } while (!self.cancelled);
    15     }
    16 }
    17 
    18 - (void)stop {
    19     self.cancelled = YES;
    20 }

    添加一个flag操控,执行stopAction后,再次操作task便又会报错,说明Runloop停止了

  • 相关阅读:
    装饰着模式
    观察者模式
    策略模式
    nginx配置图片防盗链
    nginx配置文件详解( 看着好长,其实不长,看了就知道了,精心整理,有些配置也是没用到呢 )
    php引用计数的基本知识
    PHP运行模式
    CURL常用命令--update20151015
    memcache相同主域名下的session共享
    memcached命令行操作详解,命令选项的详细解释
  • 原文地址:https://www.cnblogs.com/Walsh/p/13163288.html
Copyright © 2011-2022 走看看