Adding objects in Multidimensional NSMutableArray
Solution 1
You are add to much C to do this. This is important to know how to NSMutableArray works and how it's different compare to 2D arrays known from C/C++.
In mutable array you could store another arrays. For example:
NSMutableArray *first = [[NSMutableArray alloc] init];
NSMutableArray *second = [[NSMutableArray alloc] init];
[first addObject:second];
Now you have array in first row in first array! This is something very like C/C++ 2D arrays.
So if you want to add some object to "0,0" you do this:
NSString *mytest = [[NSString alloc] initWithString:@"test"];
[second addObject:mytest];
[first addObject:second];
So now your second contains NSStrings and first contains second. Now you can loop this like you want.
----EDIT: IF you want 1,0 you simply need another instance of second NSMutableArray. For example you have this array:
So here you will be have 3 elements in second array.
NSMutableArray *first = [[NSMutableArray alloc] init];
for(int i =0 ; i < your_size_condition ; i++) {//if you have size, if don't not a problem, you could use while!
NSArray *second = [[NSArray alloc] initWithObjects:"@something",@"somethingelse",@"more",nil];
[first addObject:second];
}
You may want to implement NSCopying protocol to do this.
Solution 2
If you need a fixed size array, then use plain C array. Before using dynamic ObjC array it needs to create it:
NSMutableArray* array = [NSMutableArray arrayWithCapacity:N];
for(int i=0; i<N; i++) {
[array addObject:[NSMutableArray arrayWithCapacity:M]];
}
UPD: The following methods might be helpful to work with such array:
[[array objectAtIndex:i] addObject:obj];
[[array objectAtIndex:i] insertObject:obj atIndex:j];
[[array objectAtIndex:i] replaceObjectAtIndex:j withObject:obj];
Rowie Po
Updated on June 04, 2022Comments
-
Rowie Po almost 2 years
I'm quite confused on how to add objects in multidimensional arrays.
Is initializing multidimensional arrays are the same with just a simple array?
This is my initialization.
testList = [[NSMutableArray alloc] init];
I need to do something like
testList[i][j] = item;
i tried
[[[testList objectAtIndex:i]objectAtIndex:j] addObject:item];
but it doesn't seem to work :(
-
Rowie Po almost 12 yearsnope, the sizes are dynamic, i just need to know how to add objects in something like testList[i][n]
-
Jakub almost 12 yearsin NSMutableArray you don't have to declare size first, you simply add another object. There is more like lists in c++ than arrays.
-
Rowie Po almost 12 yearshmm, i think i got what you mean, but then what if i want to add at 1,0?