我正在尝试使用 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/