2011-04-19 56 views
0

我想創建一個名爲HighscoresController的類NSObject的子類。當我按照以下方式調用init方法時,在調試器GDB: Program received signal: "EXC_BAD_ACCESS"中出現錯誤。有誰知道爲什麼?我完全被難住了。錯誤的子類化NSObject時:「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 

回答

1

此行有兩個問題:

_highscoresList = [HighscoresListOfLists objectAtIndex:kMyListNumber]; 

你失去了參照前面的方法分配的陣列 - 內存泄漏。

將其替換爲您不保留的對象的引用。在釋放對象後使用它肯定會導致您的訪問異常異常。

+0

非常感謝您的幫助,您完全正確。我用_highscoresList = [[NSMutableArray alloc] initWithArray:[HighscoresListOfLists objectAtIndex:kMyListNumber]]替換了該行:我也刪除了我之前爲_highscoresList所做的第一次分配。 – jonsibley 2011-04-19 03:02:42