将IOS数据保存到plist
我正在将这些数据写入plist文件,但每次写入时,都会replace以前的文件。 即它重写了我以前在重新加载页面时所有的数据。 我怎样才能使以前的数据坚持或有人指出我不正确的做法?
- (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]; }
要初始化数组,请使用现有文件作为源。 这将确保您添加的任何条目都不会覆盖,而是对现有数据进行更改。
所以,无论你在初始化arraysData
,使用下面的代码:
arraysData = [NSMutableArray arrayWithContentsOfFile: [self getFilePath]];
您只需要读取plist的所有数据,然后追加数据并将其写入plist
阅读所有的数据
NSMutableArray *plistArray = [NSMutableArray arrayWithContentsOfFile:pathList];
追加你的数据
[plistArray addObject:YOURDATA];
然后像这样写你的数组
[dict writeToFile:plistpath atomically:YES];
在插入之前,您将得到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 Without Overwrite和示例项目的解释。
如何对停止改写数据,IOS