2011-03-17 69 views
1

我有这样的问题。 我的NSMutableDictionaryNSMutableDictionary和NSArray

Object 10   Key 1 
Object 20   Key 2 
Object 30   Key 3 
Object 40   Key 4 
Object 50   Key 5 

然后,我有代码

NSArray*currentArray=[currentMutableDictionary allValues]; 

当我输出电流阵列我有 价值

20 
50 
30 
10 
40 

如何我可以从字典中正确添加obects数组为了?

感谢您的回答。

+0

你的意思是“按照正确的顺序”是什么意思?按键升序排列?在你的例子中,键恰好是1,2,3,4,5;在你的实际代码中,它们可以是任意的吗? (如果没有,你可能会考虑一个字典是否真的是正确的数据结构!) – 2011-03-17 14:17:32

回答

0

你可以让一个NSMutableArray代替,并添加迭代它的使用addObjectAtIndex方法的对象

+0

这是(可能)效率比我的答案.... – 2011-03-17 14:17:44

2

尝试了这一点:

NSInteger intSort(id num1, id num2, void *context) 
{ 
    int v1 = [num1 intValue]; 
    int v2 = [num2 intValue]; 
    if (v1 < v2) 
     return NSOrderedAscending; 
    else if (v1 > v2) 
     return NSOrderedDescending; 
    else 
     return NSOrderedSame; 
} 

NSArray *currentArray = [[currentMutableDictionary allValues] sortedArrayUsingFunction:intSort context:nil]; 

这应该阵列正确排序,假设你在你的字典中的NSNumber对象。

+0

Upvoted因为你击败了我! – 2011-03-17 14:18:05

+0

直接从文档也:) – 2011-03-17 14:18:45

+0

按值排序对象,而不是按键。我不知道安东想要什么。 – 2011-03-17 14:22:16

0

您可以使用keysSortedByValueUsingComparator以排序顺序提取密钥,然后创建一个可变阵列将值放入,并使用objectsForKeys:notFoundMarker:提取它们。

+0

这样可以避免你希望你的对象按字典排序而不是它们的值。如果你希望他们按价值排序,那么就去理查德·罗斯三世的建议,并用'allValues'把它们拉出来,然后对它们进行分类。 – 2011-03-17 14:25:29