1
votes

I have an NSArray of NSDictionaries which I would like to sort and remove duplicates from. The issue I am having is the NSDictionary contains two elements startYear and finishYear so I have an NSArray of Dictionary values that I would like to sort using startYear and finishYear.

The NSDictionary looks like this, They both contain string values.

starYear
finishYear

The values that are contained in both look like this -

(startYear / finishYear)
------------------------
(0 - 1999)
(1999 - 0)
(1999 - 2000)
(2001 - 2008)
(2000 - 2010)
(0 - 1999)
(0 - 2006)

should look like this -

(startYear / finishYear)
------------------------
(0 - 1999)
(1999 - 0)
(1999 - 2000)
(0 - 2006)
(2000 - 2010)
(2001 - 2008)

As you can see any repeating values have been removed. If startYear is 0 then that values is sorted by finishYear. If startYear and finishYear are avalible then its sorted into its startYear and then ordered according to finish year.

I am at a complete loss on how to even approach this, I have read up about sets etc.. But I just have no idea on how to sort according to the two elements in the NSDictionary.

I hope this is enough information to get some help, suggestions code examples anything to get me onto solving this would be greatly appreciated.

1
You can easily sort on the startYear first, then the finishYear or the reverse with the technique suggested by @Skotch but yours seems to be neither. How would you handle the range 1996-2012 for example? - aLevelOfIndirection
1996 - 2012 would appear first in this instance. if its 1996 - 0 that would appear before your example.. if its 0 - 2012 it would appear later down the array. - C.Johns

1 Answers

2
votes

For this you can use NSOrderedSet or NSArray. Let's assume an array, which you sort using a comparator. Something like this:

NSString const * kStartYear = @"startYear";
NSString const * kFinishYear = @"finishYear";

NSArray *unsortedArray = @[
                           @{kStartYear:@0,
                             kFinishYear:@1999},
                           @{@"startYear":@1999,
                             kFinishYear:@0},
                           @{kStartYear:@1999,
                             kFinishYear:@2000},
                           @{kStartYear:@2001,
                             kFinishYear:@2008},
                           @{kStartYear:@2000,
                             kFinishYear:@2010},
                           @{kStartYear:@0,
                             kFinishYear:@2006},
                           ];

NSArray *sortedArray = [unsortedArray sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
    NSDictionary *dictA = a;
    NSDictionary *dictB = b;

    NSNumber *startYear1 = dictA[kStartYear];
    NSNumber *startYear2 = dictB[kStartYear];
    return [startYear1 compare:startYear2];

    // Put in more logic for your comparison
}];


NSLog(@"sorted: %@", sortedArray);

Updated: more correct code