ios 以秒为单位的2个日期之间的差异ios
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19724469/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Difference between 2 dates in seconds ios
提问by Adam Altinkaya
I have an app where content is displayed to the user. I now want to find out how many seconds a user actually views that content for. So in my header file, I've declared an
我有一个向用户显示内容的应用程序。我现在想知道用户实际查看该内容的秒数。所以在我的头文件中,我已经声明了一个
NSDate *startTime;
NSDate *endTime;
Then in my viewWillAppear
然后在我看来WillAppear
startTime = [NSDate date];
Then in my viewWillDisappear
然后在我看来WillDisappear
endTime = [NSDate date];
NSTimeInterval secs = [endTime timeIntervalSinceDate:startTime];
NSLog(@"Seconds --------> %f", secs);
However, the app crashes, with different errors sometimes. Sometimes it's a memory leak, sometimes it's a problem with the NSTimeInterval, and sometimes it crashes after going back to the content for a second time.
但是,应用程序崩溃,有时会出现不同的错误。有时是内存泄漏,有时是NSTimeInterval的问题,有时是第二次返回内容后崩溃。
Any ideas on to fix this?
关于解决这个问题的任何想法?
采纳答案by medvedNick
since you are not using ARC, when you write
因为你没有使用 ARC,所以当你写
startTime = [NSDate date];
startTime = [NSDate date];
you do not retain startTime
, so it is deallocated before -viewWillDisappear
is called. Try
你不保留startTime
,所以它在-viewWillDisappear
被调用之前被释放。尝试
startTime = [[NSDate date] retain];
startTime = [[NSDate date] retain];
Also, I recommend to use ARC. There should be much less errors with memory management with it, than without it
另外,我建议使用ARC。使用它的内存管理应该比没有它的错误少得多
回答by TheGrumpyCoda
You should declare a property with retain for the start date. Your date is getting released before you can calculate the time difference.
您应该在开始日期声明一个带有保留的属性。在您计算时差之前,您的日期已发布。
So declare
所以声明
@property (nonatomic, retain) NSDate *startDate
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self setStartDate: [NSDate date]];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
NSLog(@"Seconds --------> %f",[[NSDate date] timeIntervalSinceDate: self.startDate]);
}
Don't forget to cleanup.
不要忘记清理。
- (void)dealloc
{
[self.startDate release];
[super dealloc];
}