我有一个模型类,保持跟踪记录由多个视图构建。它有一个NSMutableDictionary,它有我最终写入数据库的字段和值。它被保存到plist并在需要时装回。我以为我记录了我的记忆,但是当我尝试发布字典时,它会抛出EXC_BAD_ACCESS。这是我的接口:Objective C NSMutableDictionary内存管理
#import <Foundation/Foundation.h>
@interface CurrentEntryModel : NSObject {
NSMutableDictionary *currentEntry;
}
@property (nonatomic, retain) NSMutableDictionary *currentEntry;
- (void) setValue: (NSString *)value;
- (NSString *) getValue;
@end
我的理解是currentEntry应该保留,我将不得不在dealloc期间释放它。
这里是我的实现(这是不是整个类只是相关部分):
#import "CurrentEntryModel.h"
@implementation CurrentEntryModel
@synthesize currentEntry;
-(id) init {
if (self = [super init])
{
//check for file
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *file;
file = @"location.plist";
if ([fileManager fileExistsAtPath:file]){
NSLog(@"file exists");
currentEntry = [[NSMutableDictionary alloc] initWithContentsOfFile:file];
}else {
NSLog(@"file doesn't exist");
currentEntry = [[NSMutableDictionary alloc ] initWithCapacity:1];
NSDate *testDate = [NSDate date];
[currentEntry setObject:testDate forKey:@"created"];
[currentEntry writeToFile:file atomically:YES];
}
}
return self;
}
- (void) setValue: (NSString *)value {
[currentEntry setObject:value forKey:@"location"];
}
- (NSString *) getValue {
return [currentEntry objectForKey:@"location"];
}
- (void) dealloc{
[currentEntry release];
[super dealloc];
}
@end
如果我初始化这个类会自动创建字典,如果我叫组的一个或得到它看起来像字典保留,因为它会正确释放。如果该类刚刚初始化,然后没有方法被调用,它将抛出EXC_BAD_ACCESS错误。如果我没有错误,当文件不存在时,我不正确地初始化字典,因为该方法以字典而不是初始化开始。虽然每次运行该文件时都会使用该文件,但我认为这将保留该变量。
我不正确初始化字典吗?
编辑 - 更改便利方法上的代码以反映正确的方式。每个人都注意到Squeegy必须说的话。
我欣赏关于类方法的信息,但是我在我的问题中已经说过,这不是错误的来源 - “虽然每次运行此文件时都会使用文件找到的逻辑,而我认为这将保留变量'。有没有人有任何想法? – Joshua 2011-04-07 01:51:01