我正在尝试运行下面的代码,但在"Tick“被写入控制台后,它一直锁定我的模拟器。它从不输出“to”,所以我猜它与行"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发布于 2009-10-09 00:38:22
其中,您拥有:
startTime = [NSDate date];您需要:
startTime = [[NSDate date] retain];任何不带alloc,new,init的内容都会被自动释放(经验法则)。所以发生的事情是,你正在创建NSDate,将它分配给startTime,它被自动释放(销毁),然后你试图在一个完全释放的对象上调用timeIntervalSinceNow,所以它爆炸了。
添加保留会增加保留计数,因此在自动释放后它仍然会留在周围。不过,别忘了在用完后手动释放它!
发布于 2009-10-09 01:31:50
要利用@属性,您需要这样做: self.startTime = NSDate date
https://stackoverflow.com/questions/1541219
复制相似问题