0

我有一本带有值的字典(self.dictMyDownloads):

    {
  1: {
    id: "1",
    name: "Venue Details",
    url: "http://www.sapusers.org/event_files/3338_VENUE DETAILS KB.pdf",
    file_size: "97011"
  },
  2: {
    id: "2",
    name: "another filename",
    url: "test url 2",
    file_size: "4321"
  },
  3: {
    id: "3",
    name: "Map/Directions",
    url: "http://www.sapusers.org/event_files/3337_SAP UK Location Map HB.pdf",
    file_size: "429320"
  }
}

我正在运行此代码以将主字典中的字典插入到 nsmutablearray (self.mutArrMyDownloadsDetails) 中:

for(NSDictionary *dict in [self.dictMyDownloads allKeys]){
    [self.mutArrMyDownloadsDetails addObject:[self.dictMyDownloads objectForKey:dict]];
}

但是当我显示结果时,添加到数组中的字典顺序发生了变化。

这是其显示的结果日志:

    (
        {
        "file_size" = 97011;
        id = 1;
        name = "Venue Details";
        url = "http://www.sapusers.org/event_files/3338_VENUE DETAILS KB.pdf";
    },
        {
        "file_size" = 429320;
        id = 3;
        name = "Map/Directions";
        url = "http://www.sapusers.org/event_files/3337_SAP UK Location Map HB.pdf";
    },
        {
        "file_size" = 4321;
        id = 2;
        name = "another filename";
        url = "test url 2";
    }
)

我无法理解我在哪里或做错了什么。请帮忙。

谢谢。

4

2 回答 2

0

Objects are not stored sequentially in an NSMutableDictnory and so you can not rely on the sequence they are shown in NSLog. Is it really necessary to use array there? I recommend to use only dictionary if possible.

于 2013-09-20T06:18:56.487 回答
0

另一种方法是从你的 NSMutableArray 创建一个 NSArray,通过在你的 for 循环完成时对其进行排序:

NSSortDescriptor *sortDescriptor;
sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"id" ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];

NSArray *sortedArray = [NSArray arrayWithArray:[self.mutArrMyDownloadsDetails sortedArrayUsingDescriptors:sortDescriptors]];
于 2013-09-20T07:59:28.800 回答