开发者

NSTimer Troubles

I am trying to run the code below but it keeps locking up my simulator after the "Tick" is written to the console. It never outputs "Tock" so my guess is that it has to do with the line "NSTimeInterval elapsedTime = [startTime timeIntervalSinceNow];" The IBactions are activated by buttons. timer 开发者_StackOverflow中文版and startTime are defined in the .h as NSTimer and NSDate respectively.

Can anyone tell me what I am doing wrong?

code:

- (IBAction)startStopwatch:(id)sender
{
    startTime = [NSDate date];
    NSLog(@"%@", startTime);
    timer = [NSTimer scheduledTimerWithTimeInterval:1 //0.02
                                             target:self
                                           selector:@selector(tick:)
                                           userInfo:nil
                                            repeats:YES];
}

- (IBAction)stopStopwatch:(id)sender
{
    [timer invalidate];
    timer = nil;
}

- (void)tick:(NSTimer *)theTimer
{
    NSLog(@"Tick!");
    NSTimeInterval elapsedTime = [startTime timeIntervalSinceNow];
    NSLog(@"Tock!");
    NSLog(@"Delta: %d", elapsedTime);
}

I have the following in the .h:

@interface MainViewController : UIViewController <FlipsideViewControllerDelegate> {

    NSTimer *timer;
    NSDate *startTime;
}


- (IBAction)startStopwatch:(id)sender;
- (IBAction)stopStopwatch:(id)sender;
- (void)tick:(NSTimer *)theTimer;

@property(nonatomic, retain) NSTimer *timer;
@property(nonatomic, retain) NSDate *startTime;

@end


Where you have:

startTime = [NSDate date];

You need:

startTime = [[NSDate date] retain];

Anything that is created with out an alloc, new, init will be auto-released (rule of thumb). So what is happening is you are creating the NSDate, assigning it to startTime, it's getting auto-released (destroyed), then you are trying to call timeIntervalSinceNow on an object that was fully released so it blows up.

Adding the retain increased the retain count so it still sticks around after the auto-release. Don't forget to manually release it when you're done with it though!


To take advantage of the @property you need to do: self.startTime = [NSDate date]

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜