1

我正在尝试运行下面的代码,但在将“Tick”写入控制台后,它会一直锁定我的模拟器。它从不输出“Tock”,所以我的猜测是它与“NSTimeInterval elapsedTime = [startTime timeIntervalSinceNow];”行有关 IBactions 由按钮激活。timer 和 startTime 在 .h 中分别定义为 NSTimer 和 NSDate。

谁能告诉我我做错了什么?

代码:

- (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);
}

我在.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
4

2 回答 2

4

你在哪里:

startTime = [NSDate date];

你需要:

startTime = [[NSDate date] retain];

没有 alloc、new、init 创建的任何东西都将被自动释放(经验法则)。所以发生的事情是你正在创建 NSDate,将它分配给 startTime,它会自动释放(销毁),然后你试图在一个完全释放的对象上调用 timeIntervalSinceNow,所以它会爆炸。

添加保留增加了保留计数,因此它在自动释放后仍然存在。完成后不要忘记手动释放它!

于 2009-10-09T00:38:22.153 回答
3

要利用 @property 你需要做的:self.startTime = [NSDate date]

于 2009-10-09T01:31:50.437 回答