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.
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.
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.
You can only add objects to an NSArray
, so if you want you add CGFloat
s to an array, you can use NSNumber
.
Eg:
NSNumber * aNumber = [NSNumber numberWithFloat:aFloat];
Then to get it back:
CGFloat aFloat = [aNumber floatValue];
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 ©"!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With