2011-11-18 71 views
2

我在學習如何將NSDate對象與isEqualToDateDate方法進行比較。我不明白爲什麼這個簡單的測試不會返回true並打印出NSLog。在此先感謝比較兩個NSDate對象不能正常工作

#import <Foundation/Foundation.h> 

int main (int argc, const char * argv[]) 
{ 

    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; 

    NSDate *myDate = [[NSDate alloc]initWithTimeIntervalSinceNow:4000000]; 
    NSDate *otherDate = [[NSDate alloc]initWithTimeIntervalSinceNow:4000000]; 

    NSLog(@"myDate %@",myDate); 
    NSLog(@"otherDate %@",otherDate); 

    if ([myDate isEqualToDate:otherDate]) { 

     NSLog(@"The dates are the same"); 
    }; 

    [myDate release]; 
    [otherDate release]; 
    [pool drain]; 
    return 0; 
} 

回答

9

我相信,這可能是錯的,既然你是使用initWithTimeIntervalSinceNow的對象是在稍微不同的時間被分配,從而使他們不等。

+0

是的我想你可能是對的 - 我已經改變了方法initWithTimeIntervalSince1970,一切都很好。我沒有得到的是這個方法是什麼,如果它總是返回false。任何進一步的幫助將是偉大的。 – pete

5

這兩個日期確實稍有不同。快速示例以示區別:

NSDate *one = [[NSDate alloc]initWithTimeIntervalSinceNow:4000000]; 
NSDate *two = [[NSDate alloc]initWithTimeIntervalSinceNow:4000000]; 

NSComparisonResult difference = [two compare:one]; 

NSLog(@"Date one: %@",one); 
NSLog(@"Date two: %@",two); 

NSLog(@"Exact difference: %ld",difference); 

輸出:

Date one: 2012-01-03 07:47:40 +0000 
Date two: 2012-01-03 07:47:40 +0000 
Exact difference: 1 

EDIT

isEqualToDate:返回true在下面的例子:

NSDate *one = [[NSDate alloc]initWithTimeIntervalSince1970:4000000]; 
NSDate *two = [[NSDate alloc]initWithTimeIntervalSince1970:4000000]; 
if ([one isEqualToDate:two]) NSLog(@"Equal"); 

輸出:

Equal 
+1

看http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Constants/Reference/reference.html#//apple_ref/c/tdef/NSComparisonResult 1意味着它是有序的降序 – vikingosegundo

+0

謝謝安妮,但他們的差異 - 他們打印出相同的! – pete

+0

它們以毫秒爲單位 – vikingosegundo