How can i get Original order of NSDictionary/NSMutableDictionary?

前端 未结 5 1807
[愿得一人]
[愿得一人] 2020-12-02 00:14

i have created NSMutableDictionary with 10 keys.Now i want to access NSMutableDictionary keys in a same order as it was added to NSMutableDictionary (using SetValue:* forKey

5条回答
  •  粉色の甜心
    2020-12-02 00:39

    Although @GenralMike 's answer works a breeze, it could be optimized by leaving off the unnecessary code as follows:

    1) Keep an array to hold reference to the dictionary keys in the order they are added.

    NSMutableArray *referenceArray = [[NSMutableArray alloc] init];
    NSMutableDictionary *yourDictionary = [[ NSMutableDictionary alloc] init];
    
    for (id object in someArray) {
    
         [yourDictionary setObject:object forKey:someKey];
         [referenceArray addObject:someKey]; // add key to reference array
    
    }
    

    2) Now the "referenceArray" holds all of the keys in order, So you can retrieve objects from your dictionary in the same order as they were originally added to the dictionary.

    for (NSString *key in referenceArray){
        //get object from dictionary in order
        id object = [yourDictionary objectForKey:key];
    }
    

提交回复
热议问题