NSDictionary在插入数据时不会返回键吗?

时间:2013-05-30 07:25:35

标签: iphone nsdictionary

我已经设置了一个NSDictionary并且我希望它的键作为它的排列。但是当我打印字典的日志时,它的allkeys和allkeys排序它给了我不同的输出。任何方式我可以得到NSDictionary键,因为我已经安排它我的代码如下: -

titleDics=[[NSMutableDictionary alloc] init];
[titleDics setObject:@"Exchange" forKey:@"exchange"];
[titleDics setObject:@"Order No" forKey:@"nestordernumber"];
[titleDics setObject:@"Transaction Type" forKey:@"transactiontype"];
[titleDics setObject:@"Symbol Name" forKey:@"symbolname"];
[titleDics setObject:@"Price to fill" forKey:@"pricetofill"];
[titleDics setObject:@"Exchange Order ID" forKey:@"exchangeorderid"];
[titleDics setObject:@"Status" forKey:@"status"];
[titleDics setObject:@"Price Type" forKey:@"pricetype"];
[titleDics setObject:@"Duration" forKey:@"duration"];
[titleDics setObject:@"Product Code" forKey:@"productcode"];
[titleDics setObject:@"Script Name" forKey:@"scripname"];

NSLog(@"Title Dictioanry is %@",titleDics);

NSLog(@"Title dics keys are %@",[titleDics allKeys]);

NSLog(@"Title dics sorted keys are %@",[[titleDics allKeys] sortedArrayUsingSelector:@selector(compare:)]);

输出是:-----

2013-05-30 12:51:43.924 MobileTrading[1676:11303] Title Dictioanry is {
duration = Duration;
exchange = Exchange;
exchangeorderid = "Exchange Order ID";
nestordernumber = "Order No";
pricetofill = "Price to fill";
pricetype = "Price Type";
productcode = "Product Code";
scripname = "Script Name";
status = Status;
symbolname = "Symbol Name";
transactiontype = "Transaction Type";
}
2013-05-30 12:51:43.924 MobileTrading[1676:11303] Title dics keys are (
    nestordernumber,
    productcode,
    symbolname,
    pricetype,
    exchange,
    exchangeorderid,
    pricetofill,
    scripname,
    status,
    duration,
    transactiontype
)
2013-05-30 12:51:43.924 MobileTrading[1676:11303] Title dics sorted keys are (
    duration,
    exchange,
    exchangeorderid,
    nestordernumber,
    pricetofill,
    pricetype,
    productcode,
    scripname,
    status,
    symbolname,
    transactiontype
)

我希望这些密钥按照我设置为NSDictionary的顺序,即

exchange,
nestordernumber,
transactiontype,
symbolname,
pricetofill,
exchangeorderid,
status,
pricetype,
duration,
productcode,
scripname,

2 个答案:

答案 0 :(得分:0)

  

NSMutableDictionary总是以乱序的方式返回密钥。

如果你真的想维持秩序,那么你需要做一些技巧。像...

1)01, 02 ,03之前添加Keys 序列号,按照您要添加的顺序对其进行排序。

2)修剪字符串的前两个字符并使用它。

答案 1 :(得分:0)

此链接说明了将所需字典的键存储在所需的单独数组中,然后相应地使用它们

Are keys and values in an NSDictionary ordered?