2

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

2 Answers 2

7

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);
Sign up to request clarification or add additional context in comments.

Comments

1

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];

2 Comments

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.
Using getObjects:range: would be quicker.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.