1

I am making an application in which I am populating Array by getting Plist Dictionary, and showing in table view. Everything is working fine but data is not as ordered as we write in plist.

Exception:

1-A

2-B

3-C

But on run time execution the actual result is something like this.

1-C

2-A

3-B

Am using Swift and can't find any great help on Internet because I really don't know what to write actually to find help.

So please try to provide any useful information to avoid this problem. I can provide code on demand.

Edit:

Please Check this Image That my Structure of Plist enter image description here

  • 4
    Dictionaries are unordered. – rmaddy Nov 30 '15 at 06:41
  • Okay Got your point. I'll change Dictionary to Array But can you help me with this how to get array from pList, Any stack overflow link or anything –  Nov 30 '15 at 06:44
  • Make an NSMutableArray and add objects from dictionary to that array. You can do that using a for-each loop on keys. – NSNoob Nov 30 '15 at 06:51
  • @NSNoob no, the right way to do this is with `sort` – R Menke Nov 30 '15 at 07:05
  • @RMenke I am not aware of any method to sort the `NSDictionary`. One cannot simply sort a dictionary. You can get sorted keys and use them to populate a nsmutablearray but thats about it. – NSNoob Nov 30 '15 at 07:08
  • @NSNoob i mean on the array not on the dict. the foreach will still be unsorted. Swift dictionaries have sort by the way. – R Menke Nov 30 '15 at 07:22
  • @RMenke that comment was for Asad's comment that how to get an array from plist. He already got the point that dics are unsorted and he has to get an array to sort it. – NSNoob Nov 30 '15 at 07:24
  • Thank you Please Check My Edit Answer Please Instruct me according to that –  Nov 30 '15 at 07:58

2 Answers2

0

Make a plist file like this

enter image description here

Then get the array and loop it

    let path = NSBundle.mainBundle().pathForResource("test", ofType:"plist")
    let array = NSArray(contentsOfFile: path!) as! [Dictionary<String, String>]

    for dic in array {
        let value = dic["someKey"]
    }
ZHZ
  • 2,088
  • 13
  • 16
  • Please Check My Edit Answer I also post my screenshot. –  Nov 30 '15 at 07:59
  • How about change the Item0 to Array. And get keys by dic.keys, then you can loop it to get the values. Or get values by dic.values – ZHZ Nov 30 '15 at 08:05
0

What about sorting the keys and getting the values into an array and use that:

Objective C:

NSArray *sortedKeys = [dict.allKeys sortedArrayUsingSelector: @selector(compare:)];
NSMutableArray *sortedValues = [NSMutableArray array];
for (NSString *key in sortedKeys) {
    [sortedValues addObject: dict[key]];
}

source


Swift:

let sortedKeysAndValues = sorted(dictionary) { $0.0 < $1.0 }

source

Community
  • 1
  • 1
Islam
  • 3,654
  • 3
  • 30
  • 40