iphone - 在线程上运行 NSTimer

标签 iphone nstimer nsthread runloop

我正在尝试使用 iPhone SDK 3.0 在线程上运行 NSTimer。我认为我做的一切都是正确的(新的运行循环等)。如果我在 viewDidDissappear 上调用 [timer invalidate],但会收到此错误:

bool _WebTryThreadLock(bool), 0x3986d60: Tried to obtain the web lock from a thread other than the main thread or the web thread. This may be a result of calling to UIKit from a secondary thread. Crashing now... Program received signal: “EXC_BAD_ACCESS”.

这是我的代码:

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [activityIndicator startAnimating];
    NSThread* timerThread = [[NSThread alloc] initWithTarget:self selector:@selector(timerStart) object:nil]; //Create a new thread
    [timerThread start]; //start the thread
}

-(void)timerStart
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    NSRunLoop* runLoop = [NSRunLoop currentRunLoop];
    //Fire timer every second to updated countdown and date/time
    timer = [[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(method) userInfo:nil repeats:YES] retain];
    [runLoop run];
    [pool release];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [timer invalidate];
}

当我删除使计时器无效的行时,一切正常。我是否不应该使其无效或者我是否犯了其他错误?

谢谢

最佳答案

尝试

[timer performSelector:@selector(invalidate) onThread:timerThread withObject:nil waitUntilDone:NO];

相反。您必须将timerThread设置为 View Controller 的ivar。

关于iphone - 在线程上运行 NSTimer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2201425/

相关文章:

ios - 如何使用调度或操作队列动态更改后台操作优先级。

iphone - NSString 的问题

iphone - 如何获取 UNCONFIRMED 账户的 AWSCognitoIdentityUser 对象?

ios - 从下一个 minitue 计算当前时间然后 NSTimer 不应该工作

ios - 暂停/恢复 NSTimer

cocoa - 取消运行C++代码的NSThread

iOS:导航栏中的 UIActivityIndi​​cator 没有停止

android - 视频兼容性问题 : android recorded video not played in iphone

iphone - NSMutableArray 和 NSPredicate 过滤

ios - 当它们离开屏幕时取消与 UITableViewCells 关联的 NSTimers