最简单的方法在iPhone上的两个NSDates之间循环?

Ste*_*her 5 cocoa-touch nsdate foundation

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

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

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

当然,这不起作用:没有dateByAddingDays:.即使它确实如此,也会留下一大堆自动释放的物体等待它们的毁灭.

这就是我的想法:

  • 我不能只添加一个NSTimeInterval,因为一天中的秒数可能会有所不同.
  • 我可以将其拆分为NSDateComponents一天,然后重新组装它.但这是漫长而丑陋的代码.

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

Ste*_*her 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 );
    }
Run Code Online (Sandbox Code Playgroud)

这仍然留下了自动释放对象的痕迹,但是dateByAddingComponents:toDate:options:有责任.不确定可以做些什么.


Ste*_*her 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;
}
Run Code Online (Sandbox Code Playgroud)

这很丑陋,但丑陋仅限于我的日期范围类。我的客户端代码只是:

for (id date in dateRange) {
    NSLog( @"%@ in [%@,%@]", date, startDate, endDate );
}
Run Code Online (Sandbox Code Playgroud)

我认为如果您还没有 DateRange 类,这可能是创建 DateRange 类的充分理由。