質問

So, I have an array which I retrieve from a file named "choice". My problem is that every time I go to the highscore page, it only displays the highest high score. Also, it only keeps two of the elements from array when I load it next time. Here is my code:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; 
NSString *choice = [NSString stringWithFormat:@"%@/userschoice", documentsDirectory];
NSMutableArray *array = [NSMutableArray arrayWithContentsOfFile:choice];
NSArray *sortedHighScores = [array sortedArrayUsingSelector:@selector(compare:)];
NSMutableArray *finalArray = [[NSMutableArray alloc] init];



if ([array count]!= 0)
{   
    [array removeAllObjects];


    for (id someObject in [sortedHighScores reverseObjectEnumerator])
    {
        [finalArray addObject:someObject];

    }

    if ([array count]>1){
        NSNumber *highscore3 = [finalArray objectAtIndex:1];
        highscore2Label.text = [NSString stringWithFormat:@"2. %@ seconds",[highscore3 stringValue]];
        [array addObject:highscore3];
    }
    if ([array count] > 2){
         NSNumber *highscore4 = [finalArray objectAtIndex:2];
         highscore3Label.text = [NSString stringWithFormat:@"3. %@ seconds",[highscore4 stringValue]];
         [array addObject:highscore4];

    }

    if ([array count] > 3){
        NSNumber *highscore5 = [finalArray objectAtIndex:3];
        highscore4Label.text = [NSString stringWithFormat:@"4. %@ seconds",[highscore5 stringValue]];
        [array addObject:highscore5];

    }



    if ([array count] > 4){
        NSNumber *highscore1 = [finalArray objectAtIndex:4];
        highscore5Label.text = [NSString stringWithFormat:@"5. %@ seconds",[highscore1 stringValue]];
        [array addObject:highscore1];
    }








    NSNumber *highscore2 = [finalArray objectAtIndex:0];
    highscore1Label.text = [NSString stringWithFormat:@"1. %@ seconds", [highscore2 stringValue]];
    [array addObject:highscore2];

    [array writeToFile:choice atomically:YES];
}
役に立ちましたか?

解決

There's this line:

NSMutableArray *finalArray = [[NSMutableArray alloc] init];

....followed shortly by this one:

NSNumber *highscore2 = [finalArray objectAtIndex:0];

After the first of these lines, finalArray is a mutable array that contains no objects. On the second of these lines, you try to look up the object at index 0. Except that you haven't added any objects to finalArray, so there is no object at index 0. That's illegal, so you get an exception and a crash. I'm not sure what you're trying to do with finalArray, but you can't look up objects in an array unless it actually contains some objects. You should check the array count before doing the lookup.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top