IOS Sort NSDictionary [duplicate]

送分小仙女□ 提交于 2020-01-07 08:35:29

问题


to start, this is my code :

    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL
                                                          URLWithString:url]];

    NSData *response = [NSURLConnection sendSynchronousRequest:request
                                             returningResponse:nil error:nil];

    NSDictionary *publicTimeline = [NSJSONSerialization JSONObjectWithData:response       options:0 error:&jsonParsingError];

    for (NSObject* key in publicTimeline) {
        id value = [publicTimeline objectForKey:key];
        NSLog(@"%@", key);
    }

I take few news on a webservice, and i show it in a tableView.

My problem is that these news aren't show in order.

In my webservice, the news are in order, for example i have :

    {"0":{"title":"News1"}}
    {"1":{"title":"News2"}}
    {"2":{"title":"News3"}}

etc..

but in the loop, i "loose" this order :/ And i want to have my news in this order, first the news with the index "0" after "1" etc...

(the NSDictionary seems to loose this order, for example, after my code, i have in my tableview, the news : "2", "0", "1", and not my news "0", "1", "2". )

(i tried some answers, but none seems to work in my case :( )

SOmeone to help me ? thx,


回答1:


This is what I used last time to sort the keys of my dictionary. Hope it will be easier for you to implement it :)

NSMutableArray *sortedArray = [NSMutableArray arrayWithArray:publicTimeline.allKeys];
[sortedArray sortUsingSelector:@selector(localizedStandardCompare:)];

And you should have your sorted keys in sortedArray




回答2:


You can work with that :

NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:publicTimeline];
[dict keysSortedByValueUsingComparator:^(id obj1, id obj2) {
    return (NSComparisonResult)[obj1 compare:obj2];
}];

And then USE dict instead of publicTimeline.

Hope that will help.




回答3:


Dictionaries don't have an order. Just because the server generates your JSON in a particular order doesn't mean that it is / can be maintained when you deserialise with NSJSONSerialization.

If you need to maintain the order, either:

A. Get all of the keys from the dictionary and sort them. Then, any time you need to access in order (by index), get the key from the array and use that (don't iterate the dictionary).

B. Use a different method to deserialise the JSON which can keep / provide data about the order in which things were processed (RestKit can do that for you).



来源:https://stackoverflow.com/questions/21905440/ios-sort-nsdictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!