Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make an array of CGFloats in objective c?

So I'm working on a simple iPhone game and am trying to make a local high score table. I want to make an array and push the highest scores into it. Below is the code I have so far:

    CGFloat score;
    score=delegate.score;
    NSInteger currentindex=0;
    for (CGFloat *oldscore in highscores)
    {
        if (score>oldscore)
        {
            [highscores insertObject:score atIndex:currentindex]
            if ([highscores count]>10)
            {
                [highscores removeLastObject];  

            }

        }
        currentindex+=1;
    }

The problem is that highscores is an NSMutableArray, which can only store objects. So here's my question, what is the best way to store CGFloats in an array? Is their a different type of array that supports CGFloats? Is their a simple way to turn a CGFloat into an object?

And please don't comment on the fact that I'm storing scores in the app delegate, I know it's a bad idea, but I'm not in the mood to have to make a singleton now that the apps almost done.

like image 371
meman32 Avatar asked Jul 08 '10 15:07

meman32


People also ask

How do you declare an array of objects in Objective-C?

To declare an array in Objective-C, we use the following syntax. type arrayName [ arraySize ]; type defines the data type of the array elements. type can be any valid Objective-C data type.

How do you create an integer array in Objective-C?

Initialize an Array in Objective-Cint numbers[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; Here the following statement assigns a value 4 to the 4th element number of the array. numbers[3] = 4; Since array index always starts from 0, so array with 3rd index will be the 4th element.


2 Answers

You can only add objects to an NSArray, so if you want you add CGFloats to an array, you can use NSNumber.

Eg:

NSNumber * aNumber = [NSNumber numberWithFloat:aFloat];

Then to get it back:

CGFloat aFloat = [aNumber floatValue];
like image 174
Tom Irving Avatar answered Sep 21 '22 21:09

Tom Irving


CGFloat i.e. primitive arrays can be constructed like so...

CGFloat colors[] = { 1, 0, 0, 1 };

and subsequently "used" in a fashion similar to...

CGContextSetFillColor(context, colors);

OR (more concisely, via casting)...

CGContextSetFillColor(context, (CGFloat[]){ 1, 0, 0, 1 });

C arrays gross me out... but this CAN be done with "standard ©"!

like image 33
Alex Gray Avatar answered Sep 18 '22 21:09

Alex Gray