0

我正在尝试创建一个名为 HighscoresController 的类,它是 NSObject 的子类。init当我以以下方式调用方法时,调试器中出现错误GDB: Program received signal: "EXC_BAD_ACCESS"。有谁知道为什么?我完全被难住了。

// Initialize the highscores controller
_highscoresController = [[HighscoresController alloc] init];

这是我的类实现:

#import "HighscoresController.h"
#import "Constants.h"

@implementation HighscoresController

@synthesize highscoresList = _highscoresList;

- (id) init {

    self = [super init];

    _highscoresList = [[NSMutableArray alloc] initWithCapacity:kHighscoresListLength];
    int kMyListNumber = 0;

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"highscores.plist"];

    if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) { // if settings file exists
        NSArray *HighscoresListOfLists = [[NSArray alloc] initWithContentsOfFile:filePath];
        _highscoresList = [HighscoresListOfLists objectAtIndex:kMyListNumber];
        [HighscoresListOfLists release];
    } else { // if no highscores file, create a new one
        NSMutableArray *array = [[NSMutableArray alloc] init];
        [array addObject:_highscoresList];
        [array writeToFile:filePath atomically:YES];
        [array release];
    }
    [_highscoresList addObject:[NSNumber numberWithFloat:0.0f]];

    return self;    
}

- (void) addScore:(float)score {
    // Implementation
}

- (BOOL) isScore:(float)score1 betterThan:(float)score2 {
    if (score1 > score2)
        return true;
    else
        return false;
}

- (BOOL) checkScoreAndAddToHighscoresList:(float)score {
    NSLog(@"%d",[_highscoresList count]);
    if ([_highscoresList count] < kHighscoresListLength) {

        [self addScore:score];
        [self saveHighscoresList];
        return true;

    } else {

        NSNumber *lowScoreNumber = [_highscoresList objectAtIndex:[_highscoresList count]-1];
        float lowScore = [lowScoreNumber floatValue];
        if ([self isScore:score betterThan:lowScore]) {

            [self addScore:score];
            [self saveHighscoresList];
            return true;

        }

    }

    return false;

}

- (void) saveHighscoresList {
    // Implementation
}

- (void) dealloc {
    [_highscoresList release];
    _highscoresList = nil;
    [super dealloc];
}

@end
4

1 回答 1

1

这条线有两个问题:

_highscoresList = [HighscoresListOfLists objectAtIndex:kMyListNumber];

您丢失了对之前在该方法中分配的数组的引用——内存泄漏。

您将其替换为对您不保留的对象的引用。在释放对象后使用它肯定会导致您的错误访问异常。

于 2011-04-19T02:38:21.640 回答