NSDictionary sort by keys as floats

前端 未结 3 606
一向
一向 2021-02-03 11:00

basically I have an NSDictionary with keys and values.

The keys are all numbers, but at the moment they are strings.

I want to be able to compare them as numbers

3条回答
  •  时光取名叫无心
    2021-02-03 11:33

    You can't sort a dictionary, but you can get the keys as an array, sort that, then output in that order. sortedArrayUsingComparator will do that, and you can compare the strings with the NSNumericSearch option.

    NSArray* keys = [myDict allKeys];
    NSArray* sortedArray = [keys sortedArrayUsingComparator:^(id a, id b) { 
        return [a compare:b options:NSNumericSearch]; 
    }]; 
    
    for( NSString* aStr in sortedArray ) {
        NSLog( @"%@ has key %@", [myDict objectForKey:aStr], aStr );
    }
    

提交回复
热议问题