penguinsource
penguinsource

Reputation: 1190

declaring array of an object X with unknown size objective c

How would I go about declaring an array in the .h file of an unknown size that I will calculate say in the a function inside the class ?

For example, I might have 20 or 30 NSArrays (just an example, not what I need), but I won't know the exact number when the class is first called

in implementation file..

-(id) init {
   if self = ..
       number_of_arrays = 50; // this can be whatever value
}

in .h:

int number_of_arrays;
NSArray *arrays_of_unknown_size[number_of_arrays]; // but number of arrays is not init !

Also, what is the significance of NSArray **arrays ? Would I be able to declare that in the h file, and then in the .m file, declare the actual size ?

thanks !

Upvotes: 0

Views: 560

Answers (2)

Ramy Al Zuhouri
Ramy Al Zuhouri

Reputation: 21966

Like rmaddy says, you can just allocate the array with malloc:

arrays_of_unknown_size= (NSArray**)malloc(N*sizeof(NSArray*));

You can also reallocate it with realloc, and the size may change.
Another way is to use an array containing an array:

NSMutableArray* array_of_unknown_size=[[NSMutableArray alloc]init];

Then when the array is already populated, get the single array that you want:

NSArray* myArray=[array_of_unknown_size objectAtIndex: myIndex];

Of course arrays_of_unknown_size is too long, don't use this name, it's just an example.

Upvotes: 2

rmaddy
rmaddy

Reputation: 318794

You have two choices.

1) Make it an NSArray of NSArrays, or

2) Declare it as:

NSArray **arrays_of_unknown_size;

Then you can malloc/calloc the pointer when you know the actual size. Then you need to assign an NSArray to each element of the C-array.

Upvotes: 2

Related Questions