I am trying to comprehend how I can create multi-dimensional NSMutable arrays in general. I have come across a few solutions but haven’t been able to make them work for me, so I am not sure of their validity. Now if only someone here can help me understand how to create 2-D NSMutable arrays better that would be great!
Moving to the next question, I am not sure when I should summon NSArray/NSMutableArray vs simply using a C array. In the particular case I am dealing with, I have a fixed data type
that I want to use (boolean values) and these are clearly not objects. NS and NSMutableArray are meant to hold objects, if I am not mistaken. So is this a good idea to use a regular C array vs NSMutable array?
Adding a final twist to the question on creating 2D arrays, is using NSMatrices a better alternative or even an option than creating 2D NSMutable arrays?
Thanks and major high fives to all those who read and answer this!
To create 2D array using NSMutableArrays you would need to do the following:
Note that you can add additional rows to array2D at any time. Also each row starts out
with size 0 and is empty. You can add different number of elements to each row so it
is a jagged 2D array rather than something more like a matrix which would be fixed size
(i.e. M rows x N columns.)
To set a value at a specific row and column you would do the following:
You can store C types in NSMutableArrays by wrapping them in ObjectiveC objects.
A number can be translated into an object using NSNumber. NSNumber can also wrap boolean
values. Pointers to C structs can be wrapped using NSValue objects. You can also create
NSValue objects that wrap specific Cocoa types, e.g. CGRect.
NSArrays are not modifiable. If you need to add or remove objects to an array, you should you an NSMutableArray. Otherwise use a NSArray.
NSMutableArrays and NSArrays retain the objects that are added to them, taking ownership of them. When an object is removed from an NSMutableArray it is released so that it is cleaned up. When you release an NSArray or an NSMutableArray that you no longer require, they will clean up any objects that you have added to the array. This makes memory management of
objects within arrays much easier.
You can’t add nil objects to NSArrays and NSMutableArrays.
NSMutableArray is dynamically resizing whilst C arrays are not. This makes it much easier
to deal with adding and removing objects to the array.
I would use a C array for a group of C types, e.g. ints that is fixed size and
whose values are known at compile time:
You might need to use a C array to pass data to a library with a C API, e.g. OpenGL.
Hope this helps.