从一个日期循环到另一个日期的最简单方法是什么?
我在概念上想要的是这样的:
for (NSDate *date = [[startDate copy] autorelease]; [date compare: endDate] < 0;
date = [date dateByAddingDays: 1]) {
// do stuff here
}
这当然不起作用:没有dateByAddingDays:
。即使它确实如此,它也会留下一大堆自动释放的物体等待它们的毁灭。
以下是我的想法:
NSTimeInterval
,因为一天中的秒数可能会有所不同。NSDateComponents
并在组件中添加一天,然后重新组装。但这是漫长而丑陋的代码。所以我希望有人为此尝试了一些选择,并找到了一个好的选择。有什么想法吗?
答案 0 :(得分:7)
设置一个日期组件常量并重复添加:
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *oneDay = [[NSDateComponents alloc] init];
[oneDay setDay: 1];
for (id date = [[startDate copy] autorelease]; [date compare: endDate] <= 0;
date = [calendar dateByAddingComponents: oneDay
toDate: date
options: 0] ) {
NSLog( @"%@ in [%@,%@]", date, startDate, endDate );
}
这仍然留下了自动释放对象的痕迹,但dateByAddingComponents:toDate:options:
负责。不确定能做些什么。
答案 1 :(得分:4)
如何使用 date = [date dateByAddingTimeInterval:24 * 60 * 60] 呢?
for (NSDate *date = [[startDate copy] autorelease]; [date compare: endDate] < 0;
date = [date dateByAddingTimeInterval:24 * 60 * 60] ) {
NSLog( @"%@ in [%@,%@]", date, startDate, endDate );
}
答案 2 :(得分:3)
将快速枚举添加到DateRange类:
- (NSUInteger)countByEnumeratingWithState: (NSFastEnumerationState *)state
objects: (id *)stackbuf
count: (NSUInteger)len;
{
NSInteger days = 0;
id current = nil;
id components = nil;
if (state->state == 0)
{
current = [NSCalendar currentCalendar];
state->mutationsPtr = &state->extra[0];
components = [current components: NSDayCalendarUnit
fromDate: startDate
toDate: endDate
options: 0];
days = [components day];
state->extra[0] = days;
state->extra[1] = (uintptr_t)current;
state->extra[2] = (uintptr_t)components;
} else {
days = state->extra[0];
current = (NSCalendar *)(state->extra[1]);
components = (NSDateComponents *)(state->extra[2]);
}
NSUInteger count = 0;
if (state->state <= days) {
state->itemsPtr = stackbuf;
while ( (state->state <= days) && (count < len) ) {
[components setDay: state->state];
stackbuf[count] = [current dateByAddingComponents: components
toDate: startDate
options: 0];
state->state++;
count++;
}
}
return count;
}
这很难看,但丑陋只限于我的日期范围课程。我的客户端代码只是:
for (id date in dateRange) {
NSLog( @"%@ in [%@,%@]", date, startDate, endDate );
}
我认为这可能是创建DateRange类的一个很好的理由,如果你还没有它。