我想在一个循环中增加几天,因此它会计入2012-11-10
,2012-11-11
,2012-11-12
,...
实现这一目标的最佳方式是什么?
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];
}
答案 0 :(得分:3)
如果您需要所有中级NSDate
,只需将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);
测量结果比基金会快33%。如果您不需要创建CFDates并且可以只存储CFAbsoluteTime
值,它会更快。
答案 1 :(得分: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];