Getting C-style array from objects of NSArray - objective-c

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.

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

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.

Related

NSUInteger C Array

I ran across this presentation when searching Google for TDD principles
http://qualitycoding.org/files/BowlingGame-ObjectiveC.pdf
There's something I'm not familiar with in it. There's a declaration like this:
NSUInteger _rolls[21];
NSUInteger _currentRoll;
From following the code I've found that _rolls is an array containing several uints. But I have never seen this. Is this a part of C?
I would be more familiar with
NSArray *rolls;
NSUInteger aRoll = rolls[index];
Is the [21] describing the count, or the max limit for this array?
NSUInteger _rolls[21]; is declaring a C array of NSUInteger types with a size of 21, not an NSArray.
Think about how you would declare an array in C:
type arrayName [ arraySize ];
With ints:
int rolls[5] = {1, 2, 3, 4, 5};
It works the same way.
The number in the brackets is the size of the array, the maximum number of values it can hold.
Actually, an NSArray cannot contain NSUInteger, you can only put objects in an Objective-C array.
If you want to store NSUIntegers in an array, you'll have to wrap them first:
NSArray *rolls = [NSArray arrayWithObject: #(17)];
NSUInteger aRoll = rolls[0].unsignedIntegerValue;
Or, you can use a C array like the one you saw in the PDF...

best way to populate NSArray in this algorithm

I intend to make a program that does the following:
Create an NSArray populated with numbers from 1 to 100,000.
Loop over some code that deletes certain elements of the NSArray when certain conditions are met.
Store the resultant NSArray.
However the above steps will also be looped over many times and so I need a fast way of making this NSArray that has 100,000 number elements.
So what is the fastest way of doing it?
Is there an alternative to iteratively populating an Array using a for loop? Such as an NSArray method that could do this quickly for me?
Or perhaps I could make the NSArray with the 100,000 numbers by any means the first time. And then create every new NSArray (for step 1) by using method arraywithArray? (is it quicker way of doing it?)
Or perhaps you have something completely different in mind that will achieve what I want.
edit: replace NSArray with NSMutableArray in above post
It is difficult to tell in advance which method will be the fastest. I like the block based functions, e.g.
NSMutableArray *array = ...; // your mutable array
NSIndexSet *toBeRemoved = [array indexesOfObjectsPassingTest:^BOOL(NSNumber *num, NSUInteger idx, BOOL *stop) {
// Block is called for each number "num" in the array.
// return YES if the element should be removed and NO otherwise;
}];
[array removeObjectsAtIndexes:toBeRemoved];
You should probably start with a correctly working algorithm and then use Instruments for profiling.
You may want to look at NSMutableIndexSet. It is designed to efficiently store ranges of numbers.
You can initialize it like this:
NSMutableIndexSet *set = [[NSMutableIndexSet alloc]
initWithIndexesInRange:NSMakeRange(1, 100000)];
Then you can remove, for example, 123 from it like this:
[set removeIndex:123];
Or you can remove 400 through 409 like this:
[set removeIndexesInRange:NSMakeRange(400, 10)];
You can iterate through all of the remaining indexes in the set like this:
[set enumerateIndexesUsingBlock:^(NSUInteger i, BOOL *stop) {
NSLog(#"set still includes %lu", (unsigned long)i);
}];
or, more efficiently, like this:
[set enumerateRangesUsingBlock:^(NSRange range, BOOL *stop) {
NSLog(#"set still includes %lu indexes starting at %lu",
(unsigned long)range.length, (unsigned long)range.location);
}];
I'm quite certain it will be fastest to create the array using a c array, then creating an NSArray from that (benchmark coming soon). Depending on how you want to delete the numbers, it may be fastest to do that in the initial loop:
const int max_num = 100000;
...
id *nums = malloc(max_num * sizeof(*nums));
int c = 0;
for(int i = 1; i <= max_num; i++) {
if(!should_skip(i)) nums[c++] = #(i);
}
NSArray *nsa = [NSArray arrayWithObjects:nums count:c];
First benchmark was somewhat surprising. For 100M objects:
NSArray alloc init: 8.6s
NSArray alloc initWithCapacity: 8.6s
id *nums: 6.4s
So an array is faster, but not by as much as I expected.
You can use fast enumeration to search through the array.
for(NSNumber item in myArrayOfNumbers)
{
If(some condition)
{
NSLog(#"Found an Item: %#",item);
}
}
You might want to reconsider what you are doing here. Ask yourself why you want such an array. If your goal is to manipulate an arbitrarily large collection of integers, you'll likely prefer to use NSIndexSet (and its mutable counterpart).
If you really want to manipulate a NSArray in the most efficient way, you will want to implement a dedicated subclass that is especially optimized for this kind of job.

How do I convert a c-style char* array to NSArray?

a.H:
-(NSArray *) returnarray:(int) aa
{
unsigned char arry[1000]={"aa","vv","cc","cc","dd"......};
NSArray *tmpary=arry;
return tmpary;
}
a.c:
#include "a.H"
main (){
// how do I call returnarray function to get that array in main class
}
I need that array in main and I need to retain that array function in separate class.
Can someone please provide a code example to do this?
These lines:
unsigned char arry[1000]={"aa", "vv", "cc", "cc", "dd", ...};
NSArray *tmpary=arry;
Should instead be:
unsigned char arry[1000]={"aa", "vv", "cc", "cc", "dd", ...};
NSMutableArray * tmpary = [[NSMutableArray alloc] initWithCapacity: 1000];
for (i = 0; i < 1000; i++)
{
[tmpary addObject: [NSString stringWithCString: arry[i] encoding:NSASCIIStringEncoding]];
}
This is because a C-style array (that is, int arr[10]; for example) are not the same as actual NSArray objects, which are declared as above.
In fact, one has no idea what an NSArray actually is, other than what the methods available to you are, as defined in the documentation. This is in contrast to the C-style array, which you are guaranteed is just a contiguous chunk of memory just for you, big enough to hold the number of elements you requested.
C-style arrays are not NSArray's so your assignment of arry (the definition of which has some typos, at least the unsighned part) is not valid. In addition, you call arry an array of char, but you assign it an array of null-terminated strings.
In general you need to loop and add all the elements of the C-style array to the NSArray.
I'm not sure why you must do it in main. If you want a global you can do it by declaring a global in another file. That said, you CANNOT assign a plain C data array to an objective C NSArray, which is different in nature entirely.

NSNumbers taking up less memory than ints?

I'm still very much a noob, having a lot of fun learning the basics of Objective-C, using XCode to put together some simple programs for OS-X.
I have a program which ranks a five card poker hand.
Each card in the deck is identified by its unique 'index number' (0-51)
To speed up the evaluator I thought it would be useful to have an array containing all possible combinations of five indices (there are 2598960 of these).
If I do this:
NSMutableArray *allPossibleHands = [[NSMutableArray alloc] initWithObjects: nil];
for(int i = 0; i<48; i++)
{
for(int j = i+1; j<49; j++)
{
for(int k = j+1; k<50; k++)
{
for(int m = k+1; m<51; m++)
{
for(int n = m+1; n<52; n++)
{
NSNumber *number0 = [NSNumber numberWithInt: i];
NSNumber *number1 = [NSNumber numberWithInt: j];
NSNumber *number2 = [NSNumber numberWithInt: k];
NSNumber *number3 = [NSNumber numberWithInt: m];
NSNumber *number4 = [NSNumber numberWithInt: n];
NSArray *nextCombination = [[NSArray alloc] initWithObjects: number0,number1,number2,number3,number4,nil];
[allPossibleHands addObject: nextCombination];
}
}
}
}
}
NSLog(#"finished building allPossibleHands. It contains %i objects", [allPossibleHands count]
);
everything seems to work fine, and I get a message to say that my array contains, as expected, 2598960 objects. I can then list all the elements of my array.
But I thought wrapping my ints in NSNumber objects like that must take up a lot more memory. Maybe storing the index numbers as short ints would be better.
However, if, instead of building my array as above, I do this:
`short int allPossibleHands[2598960][5]`;
intending to then use my loop to store the ints directly, I get a EXC_BAD_ACCESS error message and a note that there's no memory available to the program.
So how come I can store all those NSNumber objects, but not the ints?
Is there some rule about array construction that I'm breaking?
As always, any guidance much appreciated.
Thank You for reading this.
While the second is allocated on the stack (which is much more limited in size), the first one is allocated on the heap and is a pointer to a memory area.
This does not mean that the first one takes less space. If you allocated the second array as a pointer, the error would go away.
Also read the answers to this question.
Assuming that an NSNumber object must store the value and the type of the number, it is probably a little larger than an int.
But if your int[][] array is a local variable, it is very likely stored on the stack, and most stacks are not that large. You could use a pointer to such an array and malloc it on the heap, which probably has enough room for it.
Accessing a C array is very likely a little faster than accessing that many NSNumbers in an NSArray and extracting their values, and if this is for a card game, speed is probably an issue.
I think the problem is where you are storing your array. Is it on the stack? If so, keep in mind it's going to be 25MB so much larger than most stacks allow.

retrieving doubles in NSMutableArray converted with [NSNumber numberWithDouble:doubleVar]

I am looking for what is probably a simple answer to my novice question. I know that NSMutableArray can only hold objects, so when I put the double into the array I used the [myArray addObject:[NSNumber numberWithDouble:aValue]]; conversion method. What I need to do now is to pull the values out as doubles and average them. I believe I will use the fast enumeration method vs. FoR looping.
I just need to know how to get the following to work.
double total;
total = [myArray objectAtIndex:i]
total = [[myArray objectAtIndex:i] doubleValue];