2012-01-16 45 views
0

對於C我會初始化一個這樣的數組:初始化2 dim陣列NSMutableArray

NSInteger x [3] [10];這樣可行。

下面我有一個昏暗的數組,可以工作。想將所有這些移動到2個暗淡的數組中,我該如何初始化它?所以換句話說就是下面的代碼,並使它能夠以2維方式工作。

NSMutableArray *SRData; 

SRData = [[NSMutableArray alloc] init]; 


NSMutableDictionary *SRRow; 

SRRow = [[NSMutableDictionary alloc] init]; 

[SRRow setObject:@"Read" forKey:@"Descr"]; 
[SRRow setObject:@"Read2.png" forKey:@"Img"]; 

[SRRow setObject:@"Read the codes" forKey:@"Det"]; 

[SRData addObject:SRRow] ; 

[SRRow release]; 

回答

3

在Objective-C中,你只需要有一個數組數組來獲得第二維。據我所知,沒有速記,所以你堅持做類似如下:

NSMutableArray *firstDimension = [[NSMutableArray alloc] init]; 
for (int i = 0; i < rows; i++) 
{ 
    NSMutableArray *secondDimension = [[NSMutableArray alloc] init]; 
    [firstDimension addObject:secondDimension]; 
} 

因此,所有你會做的是(中,NSMutableDictionary在你的情況下)添加其他對象的secondDimension陣列。用法是這樣的:

[[firstDimension objectAtIndex:0] objectAtIndex:0]; 

編輯

完整的代碼示例:

NSMutableArray *SRData = [[NSMutableArray alloc] init]; //first dimension 
NSMutableArray *SRRow = [[NSMutableArray alloc] init]; //second dimension 
[SRData addObject:SRRow]; //add row to data 
[SRRow release]; 

NSMutableDictionary *SRField = [[NSMutableDictionary alloc] init]; //an element of the second dimension 
[SRField setObject:@"Read" forKey:@"Descr"]; 
//Set the rest of your objects 

[SRRow addObject:SRField]; //Add field to second dimension 
[SRField release]; 

現在,讓那個 「田」 您將使用代碼如下所示:

[[SRData objectAtIndex:0] objectAtIndex:0]; //Get the first element in the first array (the second dimension) 
+1

確實沒有方便的速記。如果你做了很多這樣的工作,內聯函數有時可能會有所幫助('Get(array,x,y)'),在某些情況下只需使用C數組而不是'NSArray' ARC有點棘手,但仍然合法。) – 2012-01-16 21:21:09

+0

感謝您的意見! – 2012-01-16 21:37:59

+0

我似乎無法完全擺脫這種困擾。當我第一次讀這是有道理的,但現在我正在嘗試編碼它,我迷路了。可能有人如何我會如何採取我的代碼上面,並添加2個維度?我認爲Ryans的例子很棒,我想我幾乎就在那裏,但是如果沒有看到一個完整的例子就不能理解它......感謝任何幫助! – 2012-01-17 01:16:12