-2

所以,我有一个数组,我从一个名为“choice”的文件中检索它。我的问题是每次我去高分页面,它只显示最高的高分。此外,当我下次加载它时,它只保留数组中的两个元素。这是我的代码:

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];
}
4

1 回答 1

0

有这样一行:

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

....紧随其后的是这个:

NSNumber *highscore2 = [finalArray objectAtIndex:0];

在这些行的第一行之后,finalArray是一个不包含任何对象的可变数组。在这些行的第二行中,您尝试查找索引 0 处的对象。除了您没有向 中添加任何对象finalArray,因此索引 0 处没有对象。这是非法的,因此您会遇到异常和崩溃。我不确定你要做什么finalArray,但你不能在数组中查找对象,除非它实际上包含一些对象。在进行查找之前,您应该检查数组计数。

于 2013-09-04T23:35:31.457 回答