【发布时间】:2012-01-18 12:14:01
【问题描述】:
更新:找出一些东西并更改了代码。
当我将 NSDictionary 添加到我的数组时,它突然替换了我上次添加的上一个字典。我不知道为什么会这样。我正在使用 plist 作为数据存储。
我收到如下错误消息:
线程 1:程序接收信号:“EXC_BAD_ACCESS”。
初始化
-(id)init{
self=[super init];
if(self){
dbArray = [[NSMutableArray alloc] init];
}
return self;
}
添加新项目。
-(void)addNewItem:(NSString *)aString
{
// Creates a mutable dictionary with a anonymous string under the NAME key.
NSDictionary *newString = [[NSDictionary alloc] initWithObjectsAndKeys:aString,@"name", nil];
// Adds the new string to empty dbArray.
[dbArray addObject:(newString)];
NSLog(@"[add]:Added anonymous string to dbArray, under name key.");
// Writes the current dbArray (with the dict) to plist and releases retain counts.
[self writeItem];
[newString release];
}
我查看数据的方法。
-(void)viewData
{
// View data from the created plist file in the Documents directory.
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *finalPath = [documentsDirectory stringByAppendingPathComponent:@"data.plist"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:finalPath]) {
self.dbArray = [NSMutableArray arrayWithContentsOfFile:finalPath];
}
else {
self.dbArray = [NSMutableArray array];
}
}
【问题讨论】:
-
您一直在写入文件新数组。 Mb 你应该删除
self.dbArray = [[NSMutableArray alloc] init];。您将附加您的数组并正确重写它。 -
也许您的
addNewItem方法不只是添加。看起来您正在分配和初始化一个新数组,然后再向它添加新值。这将给出一个只有新值的新数组。 -
@RomanTemchenko 我已经尝试删除
self.dbArray = [[NSMutableArray alloc] init];并且当我这样做时它不会将字典保存到数组和 plist 中。 -
@Ravin455 检查
dbArray是否存在于addNewItem:中。你在addNewItem:之前打电话给viewData吗? -
@RomanTemchenko 是的,我在
addNewItem之前打电话给viewData。
标签: ios arrays plist file-writing nsdocumentdirectory