问题描述
|
我正在尝试创建一个名为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
解决方法
这行有两个问题:
_highscoresList = [HighscoresListOfLists objectAtIndex:kMyListNumber];
您将丢失对该方法前面分配的数组的引用-内存泄漏。
您将其替换为对您不保留的对象的引用。在释放对象之后使用此方法肯定会导致您的错误访问异常。