问题描述
我有两个 NSDateComponents
,我想要这两个之间的所有 NSDateComponents
,我尝试了以下方法,
NSDateComponents *first = ...;NSDateComponents *second = ...;BOOL boolDone = 否;而 (!boolDone) {[数组添加对象:第一个];第一天+=1;NSLog(@"%@",first);if([[第一个日期] 比较:[第二个日期]] == NSOrderedSame){boolDone = 是;}}NSLog(@"所有日期:%@",array);
在循环之后,它只打印我在first NSDateComponent
中的日期...!!怎么了?
这是一个需要理解的日志
2014-01-18 19:47:16.413 testCalendar[4274:a0b]
日历年:2014月份:1闰月:无天数:19
2014-01-18 19:47:16.415 testCalendar[4274:a0b]
日历年:2014月份:1闰月:无天数:20
2014-01-18 19:47:16.416 testCalendar[4274:a0b]
日历年:2014月份:1闰月:无天:21
2014-01-18 19:47:16.416 testCalendar[4274:a0b]
日历年:2014月份:1闰月:无天数:22
2014-01-18 19:47:16.417 testCalendar[4274:a0b]
日历年:2014月份:1闰月:无天数:23
2014-01-18 19:47:16.418 testCalendar[4274:a0b]
23-1-2014
23-1-2014
23-1-2014
23-1-2014
23-1-2014
解决方案您总是将相同的元素添加到数组中.数组只保存指针到它的元素,因此在循环结束时,它包含 n 个指向相同元素的指针对象first
.改变
[array addObject:first];
到
[array addObject:[第一个副本]];
应该可以解决问题.
I've two NSDateComponents
, I want all NSDateComponents
in between those two, I've tried the following,
NSDateComponents *first = ...;
NSDateComponents *second = ...;
BOOL boolDone = NO;
while (!boolDone) {
[array addObject:first];
first.day+=1;
NSLog(@"%@",first);
if([[first date] compare:[second date]] == NSOrderedSame)
{
boolDone = YES;
}
}
NSLog(@"All dates : %@",array);
After the loop, it just prints the date I've in first NSDateComponent
...!! What's wrong?
Here's a log to understand
2014-01-18 19:47:16.413 testCalendar[4274:a0b]
Calendar Year: 2014
Month: 1
Leap month: no
Day: 19
2014-01-18 19:47:16.415 testCalendar[4274:a0b]
Calendar Year: 2014
Month: 1
Leap month: no
Day: 20
2014-01-18 19:47:16.416 testCalendar[4274:a0b]
Calendar Year: 2014
Month: 1
Leap month: no
Day: 21
2014-01-18 19:47:16.416 testCalendar[4274:a0b]
Calendar Year: 2014
Month: 1
Leap month: no
Day: 22
2014-01-18 19:47:16.417 testCalendar[4274:a0b]
Calendar Year: 2014
Month: 1
Leap month: no
Day: 23
2014-01-18 19:47:16.418 testCalendar[4274:a0b]
23-1-2014
23-1-2014
23-1-2014
23-1-2014
23-1-2014
解决方案You always add the same element to the array. The array just hold pointers to its
elements, therefore at the end of the loop, it contains n pointers to the same
object first
. Changing
[array addObject:first];
to
[array addObject:[first copy]];
should solve the problem.