How to make an C vector or array from an NSArray?
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.
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);
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];
精彩评论