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

Rat*_*tan 42 iphone objective-c nsmutabledictionary

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

Joh*_*ker 81

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

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

[testDictionary release];
Run Code Online (Sandbox Code Playgroud)

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

  • 它告诉我键必须是`NSString*`,并通过`NSKeyValueCoding.h`搜索它看起来像所有方法都期望字符串.SDK中有什么变化吗? (3认同)

bbu*_*bum 8

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