在iPhone上两个NSDates之间循环的最简单的方法? [英] Simplest way to loop between two NSDates on iPhone?
本文介绍了在iPhone上两个NSDates之间循环的最简单的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
从一个日期循环到另一个日期的最简单的方法是什么?
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] autorelease]; [date compare: endDate] < 0;
date = [date dateByAddingDays: 1]) {
// do stuff here
}
当然:没有 dateByAddingDays:
。
这是我想到的:
- 我不能只添加一个
NSTimeInterval
,因为一天中的秒数可能不同。 li>
- 我可以将其分解为
NSDateComponents
,并向组件添加一天,然后重新组装。但是这是冗长而又丑陋的代码。
- I can't just add an
NSTimeInterval
, since the number of seconds in a day can vary. - I could break it down into
NSDateComponents
and add one day to the components, then reassemble it. But that's long and ugly code.
所以我希望有人尝试了几个选项,找到了一个好的。任何想法?
So I'm hoping someone has tried a few options for this, and found a good one. Any ideas?
推荐答案
为DateRange类添加快速枚举:
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 );
}
我认为这可能是一个很好的原因创建一个DateRange类如果你没有一个。
I think this is probably a good enough reason to create a DateRange class if you don't have one already.
这篇关于在iPhone上两个NSDates之间循环的最简单的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文