Simplest way to loop between two NSDates on iPhone?

后端 未结 3 890
长情又很酷
长情又很酷 2020-12-10 08:21

What\'s the simplest way to loop from one date to another?

What I want conceptually is something like this:

for (NSDate *date = [[startDate copy] aut         


        
3条回答
  •  佛祖请我去吃肉
    2020-12-10 08:49

    Add fast enumeration to a DateRange class:

    - (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;
    }
    

    This is ugly, but the ugliness is confined to my date range class. My client code is just:

    for (id date in dateRange) {
        NSLog( @"%@ in [%@,%@]", date, startDate, endDate );
    }
    

    I think this is probably a good enough reason to create a DateRange class if you don't have one already.

提交回复
热议问题