在线程上运行 NSTimer
我正在尝试使用 iPhone SDK 3.0 在线程上运行 NSTimer。我认为我做的一切都是正确的(新的运行循环等)。如果我在 viewDidDissappear 上调用 [timer invalidate],但会收到此错误:
bool _WebTryThreadLock(bool),0x3986d60:尝试从主线程或 Web 线程以外的线程获取 Web 锁。这可能是从辅助线程调用 UIKit 的结果。现在崩溃了... 程序收到信号:“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];
}
当我删除使计时器无效的行时,一切正常。我不应该使其无效还是我犯了其他错误?
谢谢
I am trying to run a NSTimer on a thread using iPhone SDK 3.0. I think I am doing everything correctly (new runloop etc.). If I call [timer invalidate] on viewDidDissappear though I get this error:
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”.
Here is my code:
- (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];
}
When I remove the line invalidating the timer everything works fine. Am I not supposed to invalidate it or am I making some other mistake?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试
一下。您必须将timerThread设置为视图控制器的ivar。
Try
instead. You will have to make timerThread an ivar of your view controller.
我猜你已经在“
method
”中完成了一些 UI 工作。从日志来看,您似乎已经在“方法”的“计时器”线程中完成了 UI 更新工作。
您可以使用 block 在主线程上分派工作或使用
performSeletorOnMainThread
执行“方法”I guess you have done some UI work in "
method
".From the log, it seems you have done UI updating work it in "Timer" thread in "method".
you can use block to dispatch work on main thread or
performSeletorOnMainThread
for doing "method"