2011-01-27 82 views

回答

76

檢索它作爲NSDictionarys僅設計用於對付的對象,一個簡單的方法做,這是包裝的整數和浮點在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等方法。

2

它需要是一個對象,所以請使用[NSNumber numberWithInt:myInteger]

然後,-integerValue

+1

integerValue方法返回一個NSInteger對象,而不是int。 :-) – 2011-01-27 10:44:57

+0

哎唷,那應該是-intValue。謝謝middaparka – sidyll 2011-01-27 10:48:40

+3

@middaparka:NSInteger不是一個對象。 – EmptyStack 2011-01-27 10:49:29

8

您可以使用NSMapTable,因爲它直接支持整數鍵和/或值。無需通過NSNumber進行裝箱/取消裝箱,但設置和使用起來也稍微困難。