views:

76

answers:

2

In my project I roll through a bunch of sql records and populate a NSMutableDictionary with a string for each key. The keys are important because I use them as section titles in my TableView.

The problem I have is that I would like the sections in a certain order. When I call allKeys the order of the keys isn't the same as the order they went into the NSMutableDictionary. I more or less understand why. My question is how I can make certain values (non alphabetically) appear first before the rest of the values.

Example strings: 'Blue', 'Brown', 'Green', 'Orange', 'Purple', 'Red', 'Violet', 'Yellow'...

I would like to see them ordered like this: 'Red', 'Green', 'Blue', 'Brown', 'Orange', 'Purple', 'Red', 'Violet'

The important part is the "'Red', 'Green', 'Blue'", all other values can be in alphabetical order behind those 3 values.

The only thing I can think of is to order them alphabetically by saying 'sortedArrayUsingSelector:@selector(compare:)' and then just trying to remove the strings I am looking for and placing them back in at a smaller index value if they exist. Any better ideas? I am not sure how efficient that is.

A: 

Your approach seems ok. Using the "stock methods" is a good choice. As you cannot make assumptions on the order of keys, this is the way to go.

Eiko
Tried my idea and it didn't work out as I had hoped. The NSMutableDictionary didn't keep them in the order I specified with the index.
SonnyBurnette
NM, I got it. I was getting a weird order because of the way I was looping. It's good now.
SonnyBurnette
A: 

Here is the method I came up with. Again, I am not sure how efficient it is, but it works for my purposes.

-(NSArray *)rearrangeSections:(NSArray *)s {
    NSArray *topSections = [NSArray arrayWithObjects:@"Red", @"Green", @"Blue", nil];

    NSArray *reversedTopSections = [[topSections reverseObjectEnumerator] allObjects];
    NSArray *alphabetizedArray = [s sortedArrayUsingSelector:@selector(compare:)];
    NSMutableArray *sections = [NSMutableArray arrayWithArray:alphabetizedArray];

    //Loop through our list of sections and place them at the top of the list.
    for (NSString *sectionTitle in reversedTopSections) {
        if ([sections containsObject:sectionTitle]) {
            [sections removeObject:sectionTitle];
            [sections insertObject:sectionTitle atIndex:0];
        }
        //NSLog(@"%@", sections);
    }

    NSArray *sortedSections = [NSArray arrayWithArray:sections];
    return sortedSections;
}
SonnyBurnette