3

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

bool _WebTryThreadLock(bool), 0x3986d60: 试图从主线程或web线程以外的线程获取web lock。这可能是从辅助线程调用 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];
}

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

谢谢

4

3 回答 3

7

尝试

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

反而。您必须使timerThread成为您的视图控制器的 ivar。

于 2010-02-04T16:57:03.957 回答
2
    - (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    NSThread* timerThread = [[NSThread alloc] initWithTarget:self selector:@selector(timerStart) userInfo:nil repeats:TRUE];
    [timerThread start]; 
    }

    -(void)timerStart
    {
   @autoreleasePool{
    NSRunLoop *TimerRunLoop = [NSRunLoop currentRunLoop];
    [NSTimer scheduleTimerWithInterval:0.1 target:self selector:@selector(methodName:) userInfo:nil repeat:YES];
    [TimerRunLoop run];
    }

    - (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    }
于 2012-10-19T11:42:22.620 回答
0

我猜你已经在“ method”中做了一些 UI 工作。

 timer = [[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(method) userInfo:nil repeats:YES] retain];

从日志中,您似乎已经在“方法”的“定时器”线程中完成了 UI 更新工作。

您可以使用块在主线程上调度工作或performSeletorOnMainThread执行“方法”

于 2012-06-19T06:03:57.127 回答