从NSArray创建NSDictionary(Objective-c 2.0)

时间:2011-12-22 00:10:34

标签: objective-c hash nsarray nsdictionary

我有一个NSArray包含索引0, 1 ... n-1的n个元素。我想用我的数组的内容填充NSDictionary

具体来说,字典应包含键值对,其中键是数组中第i个元素的哈希值,值是数组的索引。

例如:array = [123, 101, 199]然后字典将包含三个键值对:

  • ([123 hash], 0)
  • ([199 hash], 2)
  • ([101 hash], 1)

我在数组上使用for循环完成了这个。 这样做有什么更简洁的方法?也许来自NSKeyValueCoding的东西?

更多信息:我在考虑这样的事情:

NSArray *keys = [myArray valueForKey:@"hash"];
NSArray *values = [myArray valueForKey:@"index"]; // @"index" needs to change
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:values 
                                                       forKeys:keys];

2 个答案:

答案 0 :(得分:1)

for循环非常好,特别是如果你需要索引。否则你可能会使用快速枚举:

int i = 0;
for (object in array) {
  … [NSNumber numberWithInt: i] … // Add to dict
  i++;
}

这与KVC无关。

答案 1 :(得分:1)

我可能会自己使用David的for循环解决方案,但仅仅是为了踢,而且因为我仍然试图完全绕过它们,我想出了一个使用{{1}的解决方案}:

blocks

我假设存在一个生成哈希的函数NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:[array count]]; [array enumerateObjectsUsingBlock:^ (id obj, NSUInteger idx, BOOL *stop) { [dict setObject:[NSNumber numberWithUnsignedLong:idx] forKey:hashFor(obj)]; } ]; 。您可以使用消息hashFor替换该部分,也可以将其替换为生成哈希值。