zmbdr zmbdr - 1 month ago 3x
iOS Question

How to count number of elements in multidimensional array in Objective-C

I create a multidimensional array like this:

Array = [NSMutableArray arrayWithObjects:
[NSMutableArray array],
[NSMutableArray array],nil];

[Array addObject:@"0"];
[Array addObject:@"1"];
[Array addObject:@"2"];

[[Array objectAtIndex:0] addObject:@"5"];
[[Array objectAtIndex:0] addObject:@"6"];
[[Array objectAtIndex:1] addObject:@"7"];
[[Array objectAtIndex:1] addObject:@"8"];
[[Array objectAtIndex:1] addObject:@"9"];

And I want to count the number of elements in the array of "7", "8", "9" (object at index 1).
I wrote the code but it didn't work.

NSInteger count = [Array[1] count];

How can I count the number of elements of only an array(index)?


Check this code below:

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSMutableArray* myArray = [[NSMutableArray alloc] initWithObjects:[[NSMutableArray alloc] init],[[NSMutableArray alloc] init], nil];

[[myArray objectAtIndex:0] addObject:@"test00"];
[[myArray objectAtIndex:0] addObject:@"test01"];
[[myArray objectAtIndex:0] addObject:@"test02"];

[[myArray objectAtIndex:1] addObject:@"test10"];
[[myArray objectAtIndex:1] addObject:@"test11"];

NSUInteger array0Count = [[myArray objectAtIndex:0] count];
NSUInteger array1Count = [[myArray objectAtIndex:1] count];

NSLog([NSString stringWithFormat:@"array0.count=%lu,array1.count=%lu",(unsigned long)array0Count,(unsigned long)array1Count]);

Hope it can help you.