iphone-Array Won't Add NSNumber

105 views Asked by At

I am using xcode 4 to compile this application.

I am building a space game. To store my highscore values (which in this case is represented by an int, _totalSeconds), I made an array which I write to a file. Whenever the character "dies", his highscores is retrieved from the file as an array, added to the array, and written back into the file. I then call this in the highscore page of my app and use some sorting methods. However, this part is irrelevent. The problem is that after the user "dies", his highscore doesn't appear to be saved to the array. Here is my code block that comes into play after the user "dies" (by the way, this is the only code that creates this file, could it be that this file that I am calling hasn't been created yet? If so, how do I create it?):

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSNumber *highscore = [[NSNumber alloc] initWithInteger:_totalSeconds];
NSString *choice = [NSString stringWithFormat:@"%@/userschoice", documentsDirectory];
NSMutableArray *array = [NSMutableArray arrayWithContentsOfFile:choice];
[array addObject:highscore];
int test = [array count];
NSLog(@" %d",test);
[array writeToFile:choice atomically:YES];
[newText release];

The console says that [array count] = 0. I am very confused. Also, as a side-note, this app runs flawlessly in Xcode 3 (where it originated from). If you need any other information, please comment.

3

There are 3 answers

1
Jsdodgers On BEST ANSWER

I don't know why it is working on XCode 3, but the problem is that -(instancetype)arrayWithContentsOfFile:filePath returns nil if the file does not exist, which is likely the case the first time the code is called. Thus, when you are calling methods on the array, nothing happens and 0 or nil is returned, which is why you are getting zero for the length of the nil array and the item is not being added.

You need to add a condition to check if the file exists before retrieving it.

I have tested your code in my project and changing the 5th line to the following worked:

NSMutableArray *array;
if ([[NSFileManager defaultManager] fileExistsAtPath:choice]) {
    array = [NSMutableArray arrayWithContentsOfFile:choice];
}
else {
    array = [[NSMutableArray alloc] init];
}

This way, instead of getting a nil object when the file does not exist, you create a new array instead and use that to store the high scores.

0
Wain On

After this line:

NSMutableArray *array = [NSMutableArray arrayWithContentsOfFile:choice];

You need to check that array is not nil. It will be nil if no file exists (or the file contents are invalid).

So:

if (array == nil) {
    array = [NSMutableArray array];
}
0
Linda MacPhee-Cobb On

I've found I have to alloc init NSMutableArrays before they will accept any data

NSMutableArray *sortedArray = [[NSMutableArray alloc] initWithCapacity:c];