Order the Output of NSMutableDictionary like the Input

天涯浪子 提交于 2019-12-10 10:28:02

问题


how is it possbile to output the values of a dictionary in the order of input.

Example:

My Input:

    [dicValue0 setObject:@"Start Date & Time" forKey:@"START_DATETIME"];
    [dicValue0 setObject:@"Specify End" forKey:@"SPECIFY_END"];
    [dicValue0 setObject:@"End Date & Time" forKey:@"END_DATETIME"];
    [dicValue0 setObject:@"Open End" forKey:@"END_OPEN"];

Outputs:

  • Start Date & Time
  • End Date & Time
  • Specify End
  • Open End

I know how a dictionary works, but I want the output in the same order as the input!

I can write a loop which sorts me the output in the order of the input. But if i had 10000+ values that's not the best and performant way. Is there anything from apple, that helps me with this problem?


回答1:


I am pretty sure that dictionaries are not keeping track of the input order. How are you outputting the dictionary, looping through keys or just printing the dictionary?

If you know the order you want to retrieve the objects, you can create your own version of the keys array and loop through that to pull out the objects from the dictionary in your desired order




回答2:


You should create an array that keeps track of the order of the inserted keys, then iterate through that to pull values out of the dictionary. There's no built-in way to have an ordered dictionary in Foundation.




回答3:


If you want an example of how to create an ordered dictionary, check here: http://cocoawithlove.com/2008/12/ordereddictionary-subclassing-cocoa.html




回答4:


You can check this article (source code included) -

OrderedDictionary: Subclassing a Cocoa class cluster, Matt Gallagher



来源:https://stackoverflow.com/questions/8215038/order-the-output-of-nsmutabledictionary-like-the-input

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