我正在尝试运行下面的代码,但在“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
。 “非原子的,保留”不应该照顾保留问题吗?它与你的方法有什么不同? – SonnyBurnette 2009-10-09 00:44:50
它'应该',我不太熟悉@properties,但从我已经能够应付的事情来看,它应该。但是在我的测试中,它没有。我怀疑这是因为做“startTime = [NSDate日期];”直接访问该对象,而不是通过正在合成的setter属性(同样,你正在调用@synthesize,对吧?)。 虽然我的方法确实可行:-D – ACBurk 2009-10-09 01:29:39
它不访问对象,它将对象直接分配给实例变量。这就是问题所在。你不会通过该财产。 – 2009-10-10 02:54:59