如何给一个可变字典按照key
(首字母
)的来排序啊。有没有好的办法。。求教,谢谢!
NSMutableDictionary *dict=[NSMutableDictionary dictionary];
dict[@"app_key"]=@"2362558";
dict[@"fields"]=@"open_iid ";
dict[@"format"]=@"json";
ict[@"method"]=@"22222";
dict[@"timestamp"]=@"222222";
dict[@"v"]=@"2.0";
dict[@"sign_method"]=@"md5";
天蓬老师2017-04-18 09:41:54
The dictionary structure is a hash, and the hash table is sorted internally according to Hashcode. We can't sort, structurally speaking, if you want a sequential collection. This is called an array. So you’d better switch to NSArray
天蓬老师2017-04-18 09:41:54
https://github.com/sunbohong/...
I just wrote a library today that can customize sorting.
Usage
SunSortMutableDictionary *dic = [SunSortMutableDictionary new];
dic.comparator = ^(NSString* obj1,NSString* obj2){
return [obj1 compare: obj2];
};
dic[@"a"] = @"a";
dic[@"c"] = @"c";
dic[@"e"] = @"e";
NSData *data=[NSJSONSerialization dataWithJSONObject:dic options:0 error:NULL];
NSString *str=[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//str 的值为: @"{"a":"a","c":"c","e":"e"}";
XCTAssert([str isEqualToString:@"{\"a\":\"a\",\"c\":\"c\",\"e\":\"e\"}"]);
巴扎黑2017-04-18 09:41:54
You'd better tell me what problem you want to solve. Your requirement is contrary to the design of the dictionary, but it can be achieved using other auxiliary methods, such as using another array to save the key, and then getting the value from the map when the value is needed.
PHPz2017-04-18 09:41:54
I think sorting is useless. When you use it, you still have to get the value based on the key