短縮版:
でプロパティを定義し、プロパティ(nonatomic, retain)
が保持されると想定しました。しかしretain
、辞書をプロパティに割り当てるときに呼び出さないと、アプリがEXEC BAD ACCESS
エラーでクラッシュします。
長いバージョン:
辞書を持つシングルトンがあります。ヘッダーは次のように定義されます
@interface BRManager : NSObject {
}
@property (nonatomic, retain) NSMutableDictionary *gameState;
+ (id)sharedManager;
- (void) saveGameState;
@end
実装ファイルには、init で呼び出されるメソッドがあります。このメソッドは、バンドルから plist をロードし、デバイスのユーザー ドキュメント フォルダーにそのコピーを作成します。
- (void) loadGameState
{
NSFileManager *fileManger=[NSFileManager defaultManager];
NSError *error;
NSArray *pathsArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *doumentDirectoryPath=[pathsArray objectAtIndex:0];
NSString *destinationPath= [doumentDirectoryPath stringByAppendingPathComponent:@"gameState.plist"];
NSLog(@"plist path %@",destinationPath);
if (![fileManger fileExistsAtPath:destinationPath]){
NSString *sourcePath=[[[NSBundle mainBundle] resourcePath]stringByAppendingPathComponent:@"gameStateTemplate.plist"];
[fileManger copyItemAtPath:sourcePath toPath:destinationPath error:&error];
gameState = [NSMutableDictionary dictionaryWithContentsOfFile:sourcePath];
}else{
gameState = [NSMutableDictionary dictionaryWithContentsOfFile:destinationPath];
}
}
ここで、これが機能するはずだと私が考えた方法を示します。ヘッダーで、gameState プロパティを (非アトミック、保持) で定義します。「保持」とは gameState ディクショナリが保持されることを意味すると (おそらく間違って) 想定しました。ただし、シングルトン (saveGameState) には、AppDelegate -> ' applicationWillResignActive
' のときに呼び出される別のメソッドがあります。
- (void) saveGameState
{
NSArray *pathsArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *doumentDirectoryPath=[pathsArray objectAtIndex:0];
NSString *plistPath = [doumentDirectoryPath stringByAppendingPathComponent:@"gameState.plist"];
[gameState writeToFile:plistPath atomically:YES];
}
EXEC BAD ACCESS
これにより、 でエラーがスローされgameState
ます。gameState ディクショナリを保持するように loadGameState を変更すると、すべてが正常に機能します。例えば:
gameState = [[NSMutableDictionary dictionaryWithContentsOfFile:sourcePath] retain];
これは正しい動作だと思いますが、なぜですか?(nonatomic, retain)
私が考えている意味ではありませんか、それとも何か他のことがここで働いていますか?
私はまだメモリ管理を本当に理解していないので、いつもこのようなことに出くわします。