我正在将这些数据写入plist文件,但每次写入时,它都会替换之前的任何内容。即,当我重新加载页面时,它会覆盖我之前拥有的任何数据。如何使之前的数据保持不变或有人指出我做的不正确?
- (IBAction)buttonClickSave:(id)sender;
{
pathList=[self getFilePath];
if(![[NSFileManager defaultManager] fileExistsAtPath:pathList])
{
[[NSFileManager defaultManager] copyItemAtPath:[[NSBundle mainBundle] pathForResource:@"adresses" ofType:@"plist" ]toPath:pathList error:nil];
}
NSString *Name = @"Names";
NSString *email = @"email";
NSString *phone = @"phone";
NSMutableArray *values = [[NSMutableArray alloc] initWithObjects:Name, email, phone, nil];
NSMutableArray *keys = [[NSMutableArray alloc] initWithObjects:kTitleKey, kEmail, kPhone, nil];
NSDictionary *dict = [[NSDictionary alloc] initWithObjects:values forKeys:keys];
[self.arraysData addObject:dict];
[self.arraysData writeToFile:pathList atomically:YES];
}
答案 0 :(得分:2)
您所要做的就是从plist读取所有数据,然后附加数据并将此数据写入plist
阅读所有数据
NSMutableArray *plistArray = [NSMutableArray arrayWithContentsOfFile:pathList];
附加数据
[plistArray addObject:YOURDATA];
然后像这样编写你的数组
[dict writeToFile:plistpath atomically:YES];
答案 1 :(得分:0)
要初始化阵列,请使用现有文件作为源。这将确保您添加的任何条目不会被覆盖,而是对现有数据进行更改。
因此,无论您在初始化arraysData
的哪个位置,请使用以下代码:
arraysData = [NSMutableArray arrayWithContentsOfFile: [self getFilePath]];
答案 2 :(得分:0)
在插入之前,您将获得plist中的所有数据值。在将数据与您的逻辑或示例进行比较之后,使用一个用于插入带有覆盖的数据
// get plist paths from root directory
NSArray *plistPath = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
// get documents path
NSString *documentsPathPlist = [paths objectAtIndex:0];
NSString *plistDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) objectAtIndex:0]; // get the path to our plist file
NSLog(plistDirectory);
NSString *plistPathRoot = [plistDirectory stringByAppendingPathComponent:@"Sample.plist"];
//This copies objects of plist to array if there is one
[array addObjectsFromArray:[NSArray arrayWithContentsOfFile:plistPathRoot]];
//If plist has less than 10 items, insert the new data. Don't use lastInsertionIndex. Else, replace one of the items.
if([array count] < 10)
{
[array addObject:[textName.text]];
}
else
{
//Update the lastInsertionIndex
lastInsertionIndex++;
lastInsertionIndex %= 10; //// array size = 10
[array replaceObjectAtIndex:lastInsertionIndex withObject:[textName.text]];
}
[array writeToFile:plistPath atomically: TRUE];
另:
下面这个链接已经解释了很多关于Plist而没有覆盖的示例项目。