Error when subclassing NSObject: "EXC_BAD_ACCESS"
I'm trying to create a class called HighscoresController which subclasses NSObject. When I call init
method in the following manner, I get an error in the debugger GDB: Program received signal: "EXC_BAD_ACCESS"
. Does anyone have any idea why? I'm completely stumped.
// Initialize the highscores controller
_highscoresController = [[HighscoresController alloc] init];
Here's my class implementation:
#import "HighscoresController.h"
#import "Constants.h"
@implementation HighscoresController
@synthesize highscoresList = _highscoresList;
- (id) init {
self = [super init];
_highscoresList = [[NSMutableArray alloc] initWithCapacity:kHighscoresListLength];
int kMyListNu开发者_运维技巧mber = 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
This line has two problems:
_highscoresList = [HighscoresListOfLists objectAtIndex:kMyListNumber];
You lose the reference to the array you allocated earlier in the method--a memory leak.
You replace it with a reference to an object that you don't retain. Using this after the object is released is certainly causing your bad access exception.
精彩评论