【发布时间】:2011-03-31 23:15:55
【问题描述】:
我有一个模型类,用于记录由多个视图构建的跟踪记录。它有一个 NSMutableDictionary,其中包含我最终写入数据库的字段和值。它被保存到 plist 并在需要时加载回来。我以为我在跟踪我的记忆,但是当我尝试释放字典时它会抛出一个 EXC_BAD_ACCESS。这是我的界面:
#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
如果我初始化这个类,它会自动创建字典,如果我调用 set 或 get 方法之一,它似乎会保留字典,因为它会正确解除分配。如果类刚刚初始化,然后没有调用任何方法,它将抛出 EXC_BAD_ACCESS 错误。如果文件不存在时我没有弄错,我没有正确初始化字典,因为该方法以字典而不是 init 开头。虽然每次我运行这个文件都在那里,所以它总是使用文件找到的逻辑,我认为这会保留变量。
我没有正确初始化字典吗?
编辑 - 更改了便捷方法的代码以反映正确的方法。大家注意一下 Squeegy 说的话。
【问题讨论】:
-
我很欣赏有关类方法的信息,但我已经在我的问题中声明这不是错误的来源 -
Although every time I run this the file is there so it always uses the the file found logic and I thought that that will retain the variable。有人有什么想法吗?
标签: iphone objective-c xcode memory-management