2009-10-09 33 views
1

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

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

代码:

- (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

如果您有:

startTime = [NSDate date]; 

您需要:

startTime = [[NSDate date] retain]; 

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

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

+0

。 “非原子的,保留”不应该照顾保留问题吗?它与你的方法有什么不同? – SonnyBurnette 2009-10-09 00:44:50

+0

它'应该',我不太熟悉@properties,但从我已经能够应付的事情来看,它应该。但是在我的测试中,它没有。我怀疑这是因为做“startTime = [NSDate日期];”直接访问该对象,而不是通过正在合成的setter属性(同样,你正在调用@synthesize,对吧?)。 虽然我的方法确实可行:-D – ACBurk 2009-10-09 01:29:39

+1

它不访问对象,它将对象直接分配给实例变量。这就是问题所在。你不会通过该财产。 – 2009-10-10 02:54:59

3

带你需要做@property的优势:我更新了我的.h代码后 self.startTime = [NSDate的日期]

+0

DOH!这很有道理。感谢您的跟进。 – SonnyBurnette 2009-10-09 01:34:50