2011-06-12 26 views
2

我想通過使用NSMutableArray分配NSInteger有沒有辦法解決這個問題? 它不能在模擬器上運行,並在運行應用程序時切斷。如何從NSMutableArray分配整數

NSInteger Section; 
NSMutableArray dataSourceSection; 

Section = (NSInteger)[dataSourceSection objectAtIndex:2]; 

謝謝。

+2

你必須放在一個NSNumber的對象 – AmineG 2011-06-12 18:46:19

回答

8

A NSMutableArray只存儲對象。 NSInteger不是一個對象,而是一個原始數據類型。有一個類NSNumber,但是,它可以用來存儲對象內的數值。這裏有一個例子。

NSNumber *five = [NSNumber numberWithInteger:5]; 
NSMutableArray *numbers = [NSMutableArray array]; 
[numbers addObject:five]; 

要獲取對象返回和檢索整數值使用,

NSNumber *firstNumber = [numbers objectAtIndex:0]; 
NSInteger valueOfFirstNumber = [firstNumber integerValue]; 
+0

數輸出整數是錯誤的。你能建議嗎? – 2011-06-13 04:17:42

0

你不能拉一個NSInteger出一個NSMutableArray的,主要是因爲你不能把任何東西,而不是對象。在你的情況下,NSNumber將是將數字放入NSMutablearray的方式。如果你這樣做,你可以很容易地得到您的對象,這是一個NSNumber的保持,並通過轉換爲NSInteger的:

NSMutableArray *array = [[NSMutableArray alloc] init]; 
// populate the array with NSNumbers 
NSInteger number = [[array objectAtIndex:2] intValue]; 
+0

不兼容的指針...和方法 - 未找到整數 – 2011-06-13 04:15:08

+0

對,對不起,隊友只是編輯了代碼,它應該是「intValue」而不是「integerValue」。你在分配和初始化數組嗎? – Ramuel 2011-06-13 05:03:16