比较两个不起作用的NSDate对象

pet*_*ete 2 cocoa objective-c

我正在学习如何将NSDate对象与isEqualToDateDate方法进行比较.我不明白为什么这个简单的测试不会返回true并打印出来NSLog.提前致谢

#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;
}
Run Code Online (Sandbox Code Playgroud)

nic*_*ljs 9

我相信,这可能是错误的,因为你正在使用initWithTimeIntervalSinceNow它,在稍微不同的时间分配对象,从而使它们不相等.


Ann*_*nne 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);
Run Code Online (Sandbox Code Playgroud)

输出:

Date one: 2012-01-03 07:47:40 +0000
Date two: 2012-01-03 07:47:40 +0000
Exact difference: 1
Run Code Online (Sandbox Code Playgroud)

编辑

isEqualToDate:返回true以下示例:

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

输出:

Equal
Run Code Online (Sandbox Code Playgroud)