How to get NSDateComponents between two NSDateComponents?

I have two NSDateComponents , I want all NSDateComponents be between the two, I 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 when I'm in the first NSDateComponent ... !! What's wrong?

Here is a magazine 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

-3
ios nsdate nsdatecomponents
source share
1 answer

You always add the same element to the array. An array simply holds pointers to elements, so at the end of the loop it contains n pointers to the same first object. Change

 [array addObject:first]; 

to

 [array addObject:[first copy]]; 

should solve the problem.

+1
source share

All Articles