search

Home  >  Q&A  >  body text

ios - 如何给一个NSMutableDictionary可变字典排序

如何给一个可变字典按照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";
黄舟黄舟2771 days ago636

reply all(5)I'll reply

  • 天蓬老师

    天蓬老师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

    reply
    0
  • 大家讲道理

    大家讲道理2017-04-18 09:41:54

    Dictionaries are inherently unordered.

    reply
    0
  • 天蓬老师

    天蓬老师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\"}"]);
     

    reply
    0
  • 巴扎黑

    巴扎黑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.

    reply
    0
  • PHPz

    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

    reply
    0
  • Cancelreply