9

I want to use two dimensional array in ios, for example I want to prepare an array for tableview datasource,

UITableViewCell array[sections][rows];

Something like this, and here I cant predeclare the size also.

Thanks

vikingosegundo
  • 52,040
  • 14
  • 137
  • 178
sachin
  • 1,015
  • 4
  • 11
  • 24
  • check [this](http://stackoverflow.com/a/4982636/845115) – Mudit Bajpai May 28 '12 at 12:23
  • 1
    A little advice... I would recommend you to not manually store your TableCells in arrays, since the cells can be reused by UITableView for better memory handling and performance, using the dequeueReusableCellWithIdentifier method. You should keep the representation of the data that you want to show in lists, arrays or whatever you like, and then bind the data to your cells in the cellForRowAtIndexPath method. – jake_hetfield May 29 '12 at 10:41

3 Answers3

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];

And this is how you select your value from array

NSMutableArray *subArray = [dataArray objectAtIndex:2];
NSLog(@"data : %@",[subArray objectAtIndex:0]);
Dilip Manek
  • 9,095
  • 5
  • 44
  • 56
Saad
  • 8,857
  • 2
  • 41
  • 51
2

set up an NSDictionary and use an NSIndexPath as the key for each cell

wattson12
  • 11,176
  • 2
  • 32
  • 34
  • 1
    Wouldn't that be very confusing if the list in the table view changed, i.e. if an item was removed from the list? Then you would need to change the keys for all following items in the list... – jake_hetfield May 28 '12 at 13:19
  • @jake_hetfield absolutely. it would only be useful for static datasources. but then storing cells in an array seems like a waste of effort to me anyway – wattson12 May 28 '12 at 13:22
1

Syntactic sugar approach. Note that this approach will not automatically create a NSMutableArray of a given size. The initial array size will be 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];
JaredH
  • 2,338
  • 1
  • 30
  • 40