Is that possible? I've seen no method that would generate a plain old C vector or array. I have just NSNumber objects in my array which I need as C vector or array.
+1
A:
If you need your C array to carry objects, you can declare it as :
id cArray[ ARRAY_COUNT ];
or
id * cArray = malloc(sizeof(id)*[array count]);
Then you can populate it using a loop:
for (int i=0 ; i<[array count] ; i++)
cArray[i] = [array objectAtIndex:i];
mouviciel
2010-05-05 09:01:09
The objects should be retained as they are put in the c array (i.e., [cArray[i] retain]) because the NSArray could be released thereby releasing all of the objects it contains.
yabada
2010-05-05 09:13:31
Using `getObjects:range:` would be quicker.
dreamlax
2010-05-05 11:28:11
+2
A:
An alternative to mouviciel's answer is to use NSArray's getObjects:range:
method.
id cArray[10];
NSArray *nsArray = [NSArray arrayWithObjects:@"1", @"2" ... @"10", nil];
[nsArray getObjects:cArray range:NSMakeRange(0, 10)];
Or, if you don't know how many objects are in the array at compile-time:
NSUInteger itemCount = [nsArray count];
id *cArray = malloc(itemCount * sizeof(id));
[nsArray getObjects:cArray range:NSMakeRange(0, itemCount)];
... do work with cArray ...
free(cArray);
dreamlax
2010-05-05 11:33:17