如何在NSMutableDictionary中使用整数值作为'key'来设置值?

时间:2011-01-27 10:26:24

标签: iphone objective-c nsmutabledictionary

如何使用整数值作为'键'在NSMutableDictionary中设置浮点值?

3 个答案:

答案 0 :(得分:79)

由于NSDictionarys仅用于处理对象,因此一种简单的方法是将整数和float包装在NSNumber对象中。例如:

NSMutableDictionary *testDictionary = [[NSMutableDictionary alloc] init];
[testDictionary setObject:[NSNumber numberWithFloat:1.23f]
                   forKey:[NSNumber numberWithInt:1]];
NSLog(@"Test dictionary: %@", testDictionary);

[testDictionary release];

要提取相关值,只需使用NSNumber类中适当的intValue,floatValue等方法。

答案 1 :(得分:8)

您可以使用NSMapTable,因为它直接支持整数键和/或值。无需通过NSNumber进行装箱/取消装箱,但设置和使用起来也稍微困难一些。

答案 2 :(得分:2)

它必须是一个对象,所以请改用[NSNumber numberWithInt:myInteger]

然后,使用-integerValue

检索它