Sorting NSMutableArray with NSDictionary inside

Discussion in 'Mac Programming' started by alexanderl, Jan 16, 2009.

  1. alexanderl macrumors newbie

    Joined:
    Jan 16, 2009
    #1
    Hi All!
    (I have to add that Im new to ObjC dev)

    I have a NSMutableArray that contains NSDictionary objects, which each contain an object and a float (NSNumber).

    Now I want to sort the Array based on the float... How do I do that?

    I'm trying with sortUsingSelector: but I dont get it to work....

    Thanks for your help!
    alex
     
  2. caveman_uk Guest

    caveman_uk

    Joined:
    Feb 17, 2003
    Location:
    Hitchin, Herts, UK
  3. alexanderl thread starter macrumors newbie

    Joined:
    Jan 16, 2009
    #3
    Thanks caveman_uk!

    Ok here is what I got so far (and what doesnt work)

    [resultsForThisTestData addObject:[NSDictionary dictionaryWithObjectsAndKeys:dpp, @"DataPoint",
    [NSNumber numberWithFloat:distance],@"Distance",nil]];


    NSSortDescriptor * sortByDistance = [[[NSSortDescriptor alloc] initWithKey:mad:"Distance" ascending:TRUE] autorelease];

    [resultdata initWithArray:[results sortedArrayUsingDescriptors:[NSArray arrayWithObjects:sortByDistance, nil]]];

    (hope that is all the code you need)

    As I said, this doesnt work and I dont see why?!?!

    Thanks!
    Alex
     
  4. stackolee macrumors newbie

    Joined:
    Sep 12, 2009
    #4
    Check out the official documentation: http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/Collections/Articles/sortingFilteringArrays.html

    This example helped me out:
    Code:
    NSSortDescriptor *lastDescriptor =
    
            [[[NSSortDescriptor alloc] initWithKey:LAST
    
                                       ascending:NO
    
                                       selector:@selector(localizedCaseInsensitiveCompare:)] autorelease];
    
    NSSortDescriptor *firstDescriptor =
    
        [[[NSSortDescriptor alloc] initWithKey:FIRST
    
                                   ascending:NO
    
                                   selector:@selector(localizedCaseInsensitiveCompare:)] autorelease];
    
    NSArray *descriptors = [NSArray arrayWithObjects:firstDescriptor, lastDescriptor, nil];
    
    sortedArray = [array sortedArrayUsingDescriptors:descriptors];
     

Share This Page