Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

iphone - removing duplicates in nsarray

how can i remove duplicates in nsarray. for instance my array contains following data. I want to compare with adjacent dates to avoid duplicates but it throughs error.

Can anyone guide me what i am going wrong

calendar first-

( 
2010-09-25 17:00:00 GMT,
"AAA",
2010-09-25 17:00:00 GMT,
"AAA",
2010-09-26 17:00:00 GMT,
"BBB",
2010-09-26 17:00:00 GMT,
"BBB",
2010-09-27 17:00:00 GMT,
"CCCC",
2010-09-27 17:00:00 GMT,
"CCC",
2010-09-28 17:00:00 GMT,
"AAA",
2010-09-28 17:00:00 GMT,
"AAA",
2010-09-29 17:00:00 GMT,
"DDDD",
2010-09-29 17:00:00 GMT,
"DDDD",
2010-09-30 17:00:00 GMT,
"BBBB"
)

my code

NSArray dates; //dates contain above values
NSMutableArray *temp_date = [[NSMutableArray alloc] init];

for (int i=0; i<[dates count]; i+=2){
    BOOL day;

    if ([dates count]-2 >i) {
        day = [[dates objectAtIndex:i] compare:[dates objectAtIndex:i+2]];
    }   

    if (day) {
        [temp_date addObject:[dates objectAtIndex:i]];
        [temp_date addObject:[dates objectAtIndex:i+1] ];
    }
}

Regards, sathish

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

You could use sets. Duplicates will be removed automatically upon creation.

NSArray *cleanedArray = [[NSSet setWithArray:dates] allObjects];

Bear in mind that a set is unordered.

As per Brent's comment, a more recent solution to the problem that will allow you to keep the elements in order.

[[NSOrderedSet orderedSetWithArray:dates] array]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...