5

从一个日期循环到另一个日期的最简单方法是什么?

我在概念上想要的是这样的:

for (NSDate *date = [[startDate copy] autorelease]; [date compare: endDate] < 0;
     date = [date dateByAddingDays: 1]) {
    // do stuff here
}

当然,这不起作用:没有dateByAddingDays:. 即使这样做了,也会留下一大堆自动释放的对象等待销毁。

这是我的想法:

  • 我不能只添加一个NSTimeInterval,因为一天中的秒数可能会有所不同。
  • 我可以将其分解为NSDateComponents组件并添加一天,然后重新组装。但这是又长又丑的代码。

所以我希望有人为此尝试了一些选择,并找到了一个好的选择。有任何想法吗?

4

3 回答 3

7

设置一个 oneDay 日期组件常量并重复添加它:

    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:是负责任的。不确定可以做些什么。

于 2010-07-28T21:16:34.800 回答
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 );
}
于 2011-08-26T15:07:09.987 回答
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 类,我认为这可能是一个足够好的理由来创建一个 DateRange 类。

于 2010-07-28T22:51:10.357 回答