我有一个NSTimer
定义如下:
timer = [NSTimer scheduledTimerWithTimeInterval:30
target:self
selector:@selector(fooBar)
userInfo:nil
repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
我想让它调用回调函数fooBar
在本例中使用后台线程。但是当我检查时if ([NSThread mainThread])
i'm always将其放在主线程上。除了从回调函数中调度线程之外还有其他方法吗?
您正在将计时器添加到主线程。您的回调也将在主线程中。要在后台线程中调度计时器,我认为您需要使用 NSOperation 子类并将计时器从操作内部调度到 [NSRunLoop currentRunLoop]main method.
#import <Foundation/Foundation.h>
@interface BackgroundTimer : NSOperation
{
BOOL _done;
}
@end
#import "BackgroundTimer.h"
@implementation BackgroundTimer
-(void) main
{
if ([self isCancelled])
{
return;
}
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:30
target:self
selector:@selector(fooBar)
userInfo:nil
repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
//keep the runloop going as long as needed
while (!_done && [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
beforeDate:[NSDate distantFuture]]);
}
@end
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)