Search code examples
iosobjective-cnsdictionaryplist

Sorting items from plist in alphabetical order


I am having a problem displaying data I am pulling from my "plist" in alphabetical order. This is the line that I am pulling some data from my "plist" and displaying it into my tableView.

[self.objects addObjectsFromArray:[[NSDictionary dictionaryWithContentsOfFile:[[NSBundle 
mainBundle] pathForResource:@"Climb Data" ofType:@"plist"]] allKeys]];

I know in Java it would be something along the lines of Collections.sort, but I can't seem to find the equivalent in Objective-C.

Thank you for any input.


Solution

  • Don't do so many things in one line of code. It makes it too hard to figure out and debug. It doesn't make the code any faster, either.

    First load the dictionary.

    Then load the keys into an array using allKeys.

    THEN create a sorted version of the array.

    NSString *path = [[NSBundle mainBundle] pathForResource:@"Climb Data" ofType:@"plist"];
    NSDictionary *dictionary =[NSDictionary dictionaryWithContentsOfFile: path];
    NSArray *keysArray = [dictionary allKeys];
    

    The final step is easy:

    NSArray *sortedArray = [keysArray sortedArrayUsingSelector: @selector(compare:)];
    

    You could also use caseInsensitiveCompare:

    There are also methods like sortedArrayUsingComparator: that take a comparator block (a block of code you provide) to sort the array. Your block of code is a primitive that compares pairs of objects in your array. The sort method calls your block repeatedly and uses the results of those calls to sort the array.