1、定时器问题
多线程
堵塞,滞后问题async
在主线程调用下面方法oop
_timer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(sendCommand:) userInfo:button repeats:YES];post
因为该定时器重复触发时间过短,只有0.05秒,而主线程又有不少事情要处理,因此就很容易形成滞后。调用该方法后,过一段时间,再调用[_timer invalidate],定时器并不会立刻中止调用sendCommand:,而是继续调用sendCommand:,直到把滞后执行的次数执行完毕。spa
把定时器加到多线程,能够解决这个问题,例:线程
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{3d
_timer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(sendCommand:) userInfo:button repeats:YES];orm
[[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSDefaultRunLoopMode];server
[[NSRunLoop currentRunLoop] run];对象
});
2、通知问题
一个对象在多线程中调用下面的方法
[[NSNotificationCenter defaultCenter]postNotificationName:@"disconnect" object:nil];
另外一个对象,做为观察者
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(disconnect) name:@"disconnect" object:nil];
当响应通知并调用对应的方法时,
- (void)disconnect
{
NSLog(@"disconnect------%@-------------",[NSThread currentThread]);
//打印出来的线程就是多线程,若是在这里处理UI界面,就要回到主线程处理,否则就会出现会出现问题(延迟好几秒)。
}
也就是说,在哪一个线程发送通知,观察者响应通知的方法就在对应的线程。
3、延时方法问题(NSDelayedPerforming)
- (void)performSelector:(SEL)aSelector withObject:(id)anArgument afterDelay:(NSTimeInterval)delay;
可见延时方法是有对应线程的,同理,取消延时执行方法,也是有对应线程的,若是线程不同,是不会取消的。
+ (void)cancelPreviousPerformRequestsWithTarget:(id)aTarget selector:(SEL)aSelector object:(id)anArgument;