iOS Help with highscore

drf1229

macrumors regular
Original poster
Jun 22, 2009
237
0
For my next app update I want to add a highscore. The code bit I have for saving the score is as follows:
Code:
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.
 

AndyCodez

macrumors regular
Aug 6, 2009
187
0
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

macrumors regular
Original poster
Jun 22, 2009
237
0
Ok... I put an if statement to make sure that the file I was reading wasn't blank:

Code:
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

}
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.