2012-09-09 128 views
-3

我有一個核心數據表視圖,我比較日期。我目前使用的方法是:if ([todayDate compare: [NSDate date]]==NSOrderedAscending)。這工作完美但緩慢。我不需要知道時間的不同。任何幫助深表感謝!比較NSDate與[NSDate日期]最快的方法?

+0

你能更準確地說明什麼是慢嗎?它是'[NSDate date]'還是比較?你如何衡量緩慢? - 如果你需要'[NSDate date]'在一個包含許多元素的循環中,你只需要計算一次,這可能已經有所幫助了。 –

回答

1

我真的認爲,NSDates方法isEqualToDate:是你正在尋找。在我看來,是蘋果的方式來回答你的問題:

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

+0

嘿,感謝您的幫助,但它只告訴我日期是否等於或小於或大於。儘管謝謝您的幫助! – iDeveloper

+0

您應該閱讀文檔中的「比較日期」部分:http://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html In你需要知道的情況下我會使用' - (NSDate *)earlierDate:(NSDate *)anotherDate' –

1

一種選擇是不實際創建一個新的NSDate對象,但使用時間間隔進行比較。不知道性能,但可能值得一試。

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

我沒有測量它,但你可能也想嘗試:

NSTimeInterval i = [todayDate timeIntervalSinceNow]; 

其中結果(i)可以是正的或負的。

您也可以嘗試CFDateCompare

或者您可能想要考慮另一種表示數據庫中某個時間點的方式 - 例如CFTimeInterval(代表公共參考時間的秒數double)。

1

你應該還記得在一個局部變量的當前日期或當前時間戳:

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);