Xcode iPhone 应用程序 - NSDate timeIntervalSinceDate 问题 - 未知原因 - 请帮忙!
来自 viewcontroller.m 文件
-(void) hitButton
{
current = [NSDate date];
interval = [current timeIntervalSinceDate:last];
rate = 60 / (double)interval;
last = current;
NSString *output = [NSString stringWithFormat:@"%d bpm",rate];
[btnout setTitle:output forState:UIControlStateNormal];
}
- (void)viewDidLoad {
last = [[NSDate alloc] init];
current = [[NSDate alloc] init];
[super viewDidLoad];
}
来自 Viewcontroller 头文件
@interface RateAnalyserViewController : UIViewController {
double interval;
int rate;
NSDate *current;
NSDate *last;
IBOutlet UIButton *btnhit;
IBOutlet UIButton *btnout;
}
@property (nonatomic, retain) UIButton *btnhit;
@property (nonatomic, retain) UIButton *btnout;
-(IBAction) hitButton;
@end
你好, 我正在尝试制作一个简单的应用程序,以 BPM 形式显示某人按下按钮的速率。
由于某种原因,该应用程序在第一次按时运行良好,但在第二次按时崩溃。没有例外或给出任何关于原因的信息。我使用 NSLogs 来验证第二次调用 hitButton 方法,并确定程序崩溃@ current = [NSDate date]。
任何帮助将不胜感激。抱歉,如果我错过了什么。我是面向对象语言的新手。
谢谢,乔恩
From viewcontroller.m file
-(void) hitButton
{
current = [NSDate date];
interval = [current timeIntervalSinceDate:last];
rate = 60 / (double)interval;
last = current;
NSString *output = [NSString stringWithFormat:@"%d bpm",rate];
[btnout setTitle:output forState:UIControlStateNormal];
}
- (void)viewDidLoad {
last = [[NSDate alloc] init];
current = [[NSDate alloc] init];
[super viewDidLoad];
}
From Viewcontroller header file
@interface RateAnalyserViewController : UIViewController {
double interval;
int rate;
NSDate *current;
NSDate *last;
IBOutlet UIButton *btnhit;
IBOutlet UIButton *btnout;
}
@property (nonatomic, retain) UIButton *btnhit;
@property (nonatomic, retain) UIButton *btnout;
-(IBAction) hitButton;
@end
Hi,
I'm trying to make a simple app that displays the rate in BPM that someone presses a button.
For some reason the app works fine on the first press but crashes the second time. No exception or any info is given as to why. I've used NSLogs to verify the hitButton method is called the second time and established that the program crashes @ current = [NSDate date].
Any help would be appreciated. Sorry if I've missed anything out. Am new to OO languages.
Thanks, Jon
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Jon,问题是“当前”ivar 是自动释放的,所以下次运行循环旋转时,它就消失了(第一次工作,因为你分配了它,它创建了一个保留计数为 1 的对象,但它不是自动发布)。将 hitButton 中的行更改为此:
Jon, the issue is the "current" ivar is autoreleased so the next time the run loop spins, it's gone (works the first time cause you alloc-init'ed it which creates an object with a retain count of 1 that isn't autoreleased). Change the line in hitButton to this and you'll be good to go: