1

I have an NSArray arr. It has a bunch of NSNumber objects. I'm trying to calculate statistics analysis on the array using GNU's GSL. GSL takes parameters as C-style arrays.

Is there any mechanism that can, for example, run 'intValue' on all of the objects in a NSArray object, and convert the results that to a C-style array?

I don't really want to copy the contents of the NSArray to a C-style array, as it's a waste of space and cycles, so I'm looking for an alternative.

2 Answers 2

5

The mechanism you're describing — run intValue on all the objects in the NSArray and give a C-style array — seems to be exactly the same thing you describe as "a waste of space and cycles." It's also the only real way to do this if you need a C-style array of ints. Best approach I can think of:

int *c_array = malloc(sizeof(int) * [yourArray count]);
[yourArray enumerateObjectsWithOptions:NSEnumerationConcurrent 
                            usingBlock:^(id number, NSUInteger index, BOOL *unused) {
    c_array[index] = [number intValue];
}];
Sign up to request clarification or add additional context in comments.

2 Comments

I was hoping it would be possible to access the content directly.
would it make sense to create an Objective-C++ class that sets a passed array as a variable, then overloads the [] operator? I've been trying to figure out how to do that, if it's even possible. Seems like this would avoid allocation of memory at least, and be a little faster on enumeration - no need to copy, then iterate to read. Just read directly.
0

Try this:

id *numArray = calloc(sizeof(id), yourArray.count);
[yourArray getObjects: numArray range: NSMakeRange(0, yourArray.count)];

That gives you a C-array of NSNumbers. An alternative that gives you ints:

int *numArray = calloc(sizeof(int), yourArray.count);
for (int i = 0; i< yourArray.count; i++)
    numArray[i] = [[yourArray objectAtIndex: i] intValue];

There is no way to tell yourArray to return a C-array of ints directly. NSArray has no concept of the contents it has, except that they are ids, and must be retained and released at the right times. It can at most return a C-array of ids, as in my first example.

You could probably write your own simple array class that contains ints (or floats or doubles, etc.) directly, in an internal C array, but there is no stock class for this.

Comments

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.