4

我想在循环中增加天数,以便计数2012-11-10, 2012-11-11, 2012-11-12, ...</p>

实现这一目标的最有效方法是什么?

NSDate *iterationDate = [NSDate date];

for (int i = 0; i < 100; i++) {
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    [comps setYear:0];
    [comps setMonth:0];
    [comps setWeek:0];
    [comps setDay:1];
    [comps setHour:0];
    [comps setMinute:0];
    [comps setSecond:0];
    iterationDate = [currentCalendar dateByAddingComponents:comps toDate:iterationDate options:0];
}
4

2 回答 2

3

如果您需要所有中间NSDates,只需comps退出循环:

NSDate *iterationDate = [NSDate date];
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setYear:0];
[comps setMonth:0];
[comps setWeek:0];
[comps setDay:1];
[comps setHour:0];
[comps setMinute:0];
[comps setSecond:0];

for (int i = 0; i < 100; i++) {
    iterationDate = [currentCalendar dateByAddingComponents:comps toDate:iterationDate options:0];
}

您可以使用 CoreFoundation API 实现类似的功能:

CFCalendarRef calendar = CFCalendarCreateWithIdentifier(0, kCFGregorianCalendar);
CFAbsoluteTime at = CFAbsoluteTimeGetCurrent();
const CFOptionFlags options = 0;
for (int i = 0; i < NIter; ++i) {
    if (0 == CFCalendarAddComponents(calendar, &at, options, "d", 1)) {
        assert(0 && "uh-oh");
    }
    CFDateRef date = CFDateCreate(0, at);
    // store result
    CFRelease(date);
}
CFRelease(calendar);

这比 Foundation 快了 33%。如果您不需要创建 CFDates 并且可以简单地存储CFAbsoluteTime值,它会更快。

于 2012-11-10T08:42:24.423 回答
2

我觉得你的方式还不错,就是不要每次都分配NSDateComponents对象(comps):

NSDate *iterationDate = [NSDate date];
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setDay:1];
for (int i = 0; i < 100; i++) 
    iterationDate = [currentCalendar dateByAddingComponents:comps toDate:iterationDate options:0];

另一种方法可能是(这应该更快,但需要测试......):

NSDate *iterationDate = [NSDate date];
int daysToAdd = 1;  
for (int i = 0; i < 100; i++)
       iterationDate = [iterationDate addTimeInterval:60*60*24*daysToAdd];
于 2012-11-10T08:42:17.667 回答