這也是新手滿常見的問題, nsdictionary 裡有 name 跟 score 的值,產生一個由低分到高分的 keys 陣列。
這個方法可以自訂一些條件,nsmutabledictionary也同樣適用喔。
NSMutableDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys: [NSDictionary dictionaryWithObjectsAndKeys:@"mark", @"name", @"100", @"score", nil], @"mark", [NSDictionary dictionaryWithObjectsAndKeys:@"tom", @"name", @"78", @"score", nil], @"tom", [NSDictionary dictionaryWithObjectsAndKeys:@"mary", @"name", @"81", @"score", nil], @"mary", [NSDictionary dictionaryWithObjectsAndKeys:@"sandy", @"name", @"65", @"score", nil], @"sandy", [NSDictionary dictionaryWithObjectsAndKeys:@"sam", @"name", @"98", @"score", nil], @"sam", nil]; NSArray *blockSortedKeys = [dict keysSortedByValueUsingComparator: ^(id obj1, id obj2) { if ([[obj1 objectForKey:@"score"] intValue] > [[obj2 objectForKey:@"score"] intValue]) { return (NSComparisonResult)NSOrderedDescending; } if ([[obj1 objectForKey:@"score"] intValue] < [[obj2 objectForKey:@"score"] intValue]) { return (NSComparisonResult)NSOrderedAscending; } return (NSComparisonResult)NSOrderedSame; }];