所以,我有一个数组,我从名为“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];
}
答案 0 :(得分:0)
有这条线:
NSMutableArray *finalArray = [[NSMutableArray alloc] init];
....紧接着就是这个:
NSNumber *highscore2 = [finalArray objectAtIndex:0];
在第一行之后,finalArray
是一个不包含任何对象的可变数组。在第二行中,您尝试在索引0处查找对象。除非您没有向finalArray
添加任何对象,因此索引0处没有对象。这是非法的,因此您获得了异常和崩溃。我不确定你要用finalArray
做什么,但你不能在数组中查找对象,除非它实际上包含一些对象。在进行查找之前,您应该检查数组计数。