2012-05-28 35 views
9

我想使用IOS二維陣列,比如我想爲tableview數據源準備數組,二維數組中的IOS

UITableViewCell array[sections][rows];

這樣的事情,在這裏我不能預先聲明大小也。

感謝

+0

檢查[這](http://stackoverflow.com/a/4982636/845115) –

+1

的一點小建議,我會建議你不要手動保存數組中的TableCells,因爲單元可以被UITableView重用,以便使用dequeueReusableCellWithIdentifier方法獲得更好的內存處理和性能。 您應該保留要以列表,數組或任何您喜歡的方式顯示的數據的表示形式,然後將數據綁定到cellForRowAtIndexPath方法中的單元格。 –

回答

24
NSMutableArray *dataArray = [[NSMutableArray alloc] initWithCapacity: 3]; 

[dataArray insertObject:[NSMutableArray arrayWithObjects:@"0",@"0",@"0",nil] atIndex:0]; 
[dataArray insertObject:[NSMutableArray arrayWithObjects:@"0",@"0",@"0",nil] atIndex:1]; 
[dataArray insertObject:[NSMutableArray arrayWithObjects:@"0",@"0",@"0",nil] atIndex:2]; 

這就是你如何從陣列

NSMutableArray *subArray = [dataArray objectAtIndex:2]; 
NSLog(@"data : %@",[subArray objectAtIndex:0]); 
2

設立NSDictionary選擇你的價值和使用NSIndexPath爲重點的每個細胞

+1

如果表格視圖中的列表發生了變化,即如果某個項目已從列表中刪除,那麼這樣做會不會很混亂?然後,您需要更改列表中所有下列項目的鍵... –

+0

@jake_hetfield絕對。它只對靜態數據源有用。但是然後將數組存儲到數組中看起來像是浪費了我的努力 – wattson12

1

語法糖的方法。請注意,這種方法不會自動創建給定大小的NSMutableArray。最初的數組大小爲0,0。

NSMutableArray *yourArray = [@[ [@[] mutableCopy]] mutableCopy]; 

// add an object to the end of your array 
[yourArray[section][row] addObject:@(22)]; 

// set/change an NSNumber object at a particular location in the 2D array. 
yourArray[section][row] = @(22); 

// Retrieve a value, converting the NSNumber back to a NSInteger 
NSInteger result = [yourArray[section][row] integerValue]; 
+0

這是一個好的開始,但展示如何擴展它以展示如何添加項目以及如何訪問項目將使它成爲更完整的答案。 – Caleb

+1

添加了更多功能@Caleb – JaredH