Moe
Moe

Reputation: 4802

NSRunLoop working OK on Simulator, Crashes iDevice

I'm working on an iOS App (FW: 5.0+ & ARC) which needs to update second by second.

Currently, I have this within a method (which is called in a performSelector when -ViewDidLoad):

-(void)FireOnload {
counter = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(countDownTime) userInfo:nil repeats:YES];
[counter fire];
[[NSRunLoop mainRunLoop] addTimer:counter forMode: NSDefaultRunLoopMode]; // <-- Causing Problem
}

-(void)countDownTime
{
double timeNow = [[NSDate date] timeIntervalSince1970];
double timeLeft = timeEnding - timeNow;

if(timeLeft < 60) // Less then 60 seconds, do something.
{
   //Do Stuff
}

}

the counter variable is called in the header as NSTimer. I explicitly call [counter fire] so it is called as soon as the view is loaded, not after 1 second.

This works fine in the iOS Simulator and will fire every second, but when it goes to the iDevice, it crashes.

I've commented out the NSRunLoop line, and the iDevice does not crash. However, it no longer updates every second.

What am I doing wrong here?

Upvotes: 2

Views: 643

Answers (2)

Moe
Moe

Reputation: 4802

Found the Problem:

changed:

@property (weak, nonatomic) NSTimer *counter;

to:

@property (strong, nonatomic) NSTimer *counter;

If you're not using ARC, then you'll need to replace strong with retain

Upvotes: 2

JeremyP
JeremyP

Reputation: 86691

You say you use performSelector to invoke FireOnLoad. Why? If you are invoking it on a background thread, you need to know that NSRunLoop is not thread safe so you shouldn't access the main runloop except on the main thread.

Upvotes: 0

Related Questions