【问题标题】:Comparing NSDate to [NSDate date] Fastest Way?将 NSDate 与 [NSDate 日期] 最快的方式进行比较?
【发布时间】:2012-09-09 06:14:51
【问题描述】:

我有一个核心数据表视图,我正在比较日期。我目前使用的方法是:if ([todayDate compare: [NSDate date]]==NSOrderedAscending)。这工作得很好但很慢。不过,我不需要知道时间上的差异。非常感谢任何帮助!

【问题讨论】:

  • 你能更准确地说明什么是慢吗?是[NSDate date] 还是比较?你是如何测量缓慢的? - 如果你需要 [NSDate date] 在一个包含许多元素的循环中,你应该只计算一次,也许这已经有帮助了。

标签: iphone ios date sdk nsdate


【解决方案1】:

我真的认为,NSDates 方法isEqualToDate: 是您正在寻找的。在我看来,这是回答您问题的 Apple 方式:



NSDate *date1 = ...;
NSDate *date2 = ...;

BOOL datesAreEqual = [date1 isEqualToDate:date2];

欲了解更多信息,请访问https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/nsdate_Class/Reference/Reference.html

【讨论】:

【解决方案2】:

一种选择可能是不实际创建新的NSDate 对象,而是使用时间间隔进行比较。不知道性能如何,但可能值得一试。

if ([todayDate timeIntervalSinceReferenceDate] > [NSDate timeIntervalSinceReferenceDate]) {
...
}

【讨论】:

    【解决方案3】:

    您应该记住局部变量中的当前日期或当前时间戳:

    NSTimeInterval current = [NSDate timeIntervalSinceReferenceDate];
    

    稍后使用此值进行所有比较:

    myTimestamp = [myDate timeIntervalSinceReferenceDate]
    
    if (myTimestamp == current) {
      return NSOrderedSame;
    } else if (myTimestamp > current) {
      return NSOrderedDescending;
    } else {
      return NSOrderedAscending;
    }
    

    或者更快的方法,使用 C 函数:

    // Get the current calendar time as a time_t object.
    time_t time ( time_t * timer );
    
    // Return difference between two times
    double difftime ( time_t time2, time_t time1 );
    

    【讨论】:

      【解决方案4】:

      我没有测量过,但你可以试试:

      NSTimeInterval i = [todayDate timeIntervalSinceNow];
      

      结果 (i) 可能是正数或负数。

      你也可以试试CFDateCompare

      或者您可能想考虑另一种表示数据库中时间点的方式——例如CFTimeIntervaldouble 表示距公共参考时间的秒数)。

      【讨论】:

        猜你喜欢
        • 2011-01-16
        • 2011-07-30
        • 2013-07-06
        • 1970-01-01
        • 1970-01-01
        • 2016-12-12
        • 2012-05-30
        • 2011-07-04
        • 2014-11-29
        相关资源
        最近更新 更多