开发者

iOS: EXC_BAD_ACCESS caused by running timer in NSThread?

开发者 https://www.devze.com 2023-04-13 05:05 出处:网络
I have been having some crashes in my app.When checking the logs and using atos, it is telling me exactly where I get the crash, which is where I tell my NSRunLoop to run:

I have been having some crashes in my app. When checking the logs and using atos, it is telling me exactly where I get the crash, which is where I tell my NSRunLoop to run:

/**
 * Create a new thread for the timer
 *
 * @version $Revision: 0.1
 */
- (void)createTimerThread {
    NSThread *timerThread = [[NSThread alloc] initWithTarget:self selector:@selector(startTimerThread) object:nil];
    [timerThread start];
    [timerThread release];
}//end


/**
 * Start the actual timer
 *
 * @version $Revision: 0.1
 */
- (void)startTimerThread {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    NSRunLoop *runLoop = [NSRunLoop currentRunLoop];

    // Start timer
    self.countTimer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:sel开发者_如何学Cf selector:@selector(updateCounter:) userInfo:nil repeats:YES];

    [runLoop run];// <--- Crash happened here
    [pool release];

}//end


/**
 * Update the counter
 *
 * @version $Revision: 0.1
 */
- (void)updateCounter:(NSTimer *)theTimer {

    // Does tons of timer stuff here

}//end

As you can see, the crash happens on [runLoop run] but I have no idea why. It normally happens the second time that I call the createTimerThread method.

What am I doing wrong here? All I was wanting to do was run a timer in the background so that it wasn't on the main thread because I needed to update a UILabel.

Should I be using something new like Grand Central Dispatch (GCD)?


You said updateCounter is updating a UILabel and that's being called from the timer that's running on the background thread. You can't do that, you need to update UI views on the main thread.

You can either use performSelectorOnMainThread or GCD (dispatch to the main queue). I compared both using samples on this SO post:

GCD, Threads, Program Flow and UI Updating

This SO article specifically has an example of a bg timer with GCD:

iOS4 Create Background Timer

Look at the post from mrwalker


Any calls that involve the UI are not thread safe, meaning you have to do any updates on the main thread.

Not sure what you are actually trying to achieve. If you are doing something computationally expensive on every timer "tick", then yes GCD would be you best bet utilizing blocks.

Perhaps you could give us some insight on what your doing each tick and what your displaying in the UILabel?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号