Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
378 views
in Technique[技术] by (71.8m points)

ios - How to get NSDateComponents between two NSDateComponents?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...