IOS常见问题分析

1、定时器问题

1) 定时器在子线程中不启动:

   定时器创建有两种方式:
   方式一:NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(run:) userInfo:@"test" repeats:YES];   
   方式二:NSTimer *timer = [NSTimer timerWithTimeInterval:3.0 target:self selector:@selector(run:) userInfo::@"test" repeats:YES];
         [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
       方式一和方式二相对比,方式一其实调用了scheduledTimer方法,会自动添加到当前的runloop里面去,而且runloop的运行模式kCFRunLoopDefaultMode;
       主线程和子线程的区别在于:主线程会自动创建runloop,而子线程不会自动创建,需要手动创建,所以在主线程中timer能够添加到当前runloop中;而对于子线程而言,根本不存在runloop,所以无法添加,以致于定时器无法启动;
       由于runloop的存在,所以主线程不会死亡;而对于子线程而言,不存在runloop,所以执行完任务后就会死亡,如果要子线程不死必须在子线程中创建一个runloop。

子线程中启动定时器的方法:

     NSRunLoop *loop = [[NSRunLoop currentRunLoop];
     NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(run:) userInfo:@"test" repeats:YES];   
    [loop run];
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容