PDA

View Full Version : Help with highscore




drf1229
Dec 2, 2009, 04:23 PM
For my next app update I want to add a highscore. The code bit I have for saving the score is as follows:

NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullFileName = [NSString stringWithFormat:@"%@/highscore", documentsDirectory];
NSMutableArray *array = [[NSMutableArray alloc] initWithContentsOfFile:fullFileName];
NSString *score=[array objectAtIndex:0];
[time2 setText:score];
int score2=[[time2 text] intValue];
if (points>score2){
//Points is the
//amount of points
//just scored
NSMutableArray *array2=array;
[array2 removeObjectAtIndex:0];
[array2 insertObject:[NSString stringWithFormat:@"%i",points] atIndex:0];
printf("High score beat! New score is:%i Old score was:%i",points,score2);

[array2 writeToFile:fullFileName atomically:NO];

}
For some odd reason score2 always returns 0, yet [time2 text] is the correct score. I am completely baffled. Am I misusing "intvalue"? Any help or advice would be greatly appreciated! Edit: I recently looked at the NSString class reference provided by apple, and it said intvalue "Returns 0 if the receiver doesn’t begin with a valid decimal text representation of a number". I think this means that if the string doesn't start with a number it won't work, but that doesn't make sense because the value I wrote to the file does start with a number.



Jason Beck
Dec 2, 2009, 05:16 PM
I don't have an iPhone but that looks like an awesome start! Get this done and make a Paid app and make some money! : )

drf1229
Dec 2, 2009, 06:11 PM
I don't have an iPhone but that looks like an awesome start! Get this done and make a Paid app and make some money! : )

Thanks. I just need to solve this one problem

AndyCodez
Dec 3, 2009, 07:56 AM
I can't remember if i had an issue with this or not. Is it possible there is extra whitespace in the stored string. I cant remember if it automatically trims it or if this could cause an issue.

You might want to look into extra white space causing an issue.

drf1229
Dec 3, 2009, 02:38 PM
Oh I see I fixed it thanks!

lloyddean
Dec 3, 2009, 02:52 PM
Oh I see I fixed it thanks!

I really would like to see more folks post their final solutions rather than this type of end response.

drf1229
Dec 3, 2009, 07:08 PM
Ok... I put an if statement to make sure that the file I was reading wasn't blank:

NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullFileName = [NSString stringWithFormat:@"%@/practice", documentsDirectory];
NSMutableArray *array = [[NSMutableArray alloc] initWithContentsOfFile:fullFileName];
if([array objectAtIndex:0]!=0){

//Read from the file

}
else{

//Write default data to the file

}