我有一个简单的 Objective-C 程序,我在其中将用户输入的数据保存在 plist 中。但是当我尝试在我的 plist 中保存多个数据时,它会重写旧数据,我只能在我的 plist 中获取一个数据,即用户输入的最后一个数据。下面是我保存数据的代码-
- (IBAction)savedata:(id)sender
{
NSError *error;
NSString *arr= [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
arr=[arr stringByAppendingPathComponent:@"datalist.plist"];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSMutableArray *valuearray = [[NSMutableArray alloc]init];
NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
[dict setValue:_nametextfield.text forKey:@"NAME"];
[valuearray addObject:dict];
if ([fileManager fileExistsAtPath:arr])
{
NSLog(@"FILE EXIST");
self.bundle = [[NSBundle mainBundle]pathForResource:@"datalist" ofType:@"plist" ];//NSString *bundle = [[NSBundle mainBundle] pathForResource:@”data” ofType:@”plist”];
NSLog(@"%@",_bundle);
[fileManager copyItemAtPath:_bundle toPath: arr error:&error];
[valuearray writeToFile:arr atomically:YES];
NSLog(@"%@",arr);
//6
}
else
{
NSLog(@"FILE DOESN'T EXIST");
[valuearray writeToFile:arr atomically:YES];
}
}
这是我获取的数据 -
- (IBAction)fetchdata:(id)sender
{
NSString *arr= [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
arr=[arr stringByAppendingPathComponent:@"datalist.plist"];
if ([[NSFileManager defaultManager]fileExistsAtPath:arr])
{
NSArray *dict=[NSArray arrayWithContentsOfFile:arr];
NSLog(@"%@",dict);
}
}
最佳答案
用这个替换保存部分 -
- (IBAction)savedata:(id)sender
{
NSError *error;
NSString *arr= [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
arr=[arr stringByAppendingPathComponent:@"datalist.plist"];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSMutableArray *valuearray = [[NSMutableArray alloc]init];
NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
[dict setValue:_titletextfield.text forKey:@"NAME"];
[valuearray addObject:dict];
if ([fileManager fileExistsAtPath:arr])
{
NSLog(@"FILE EXIST");
//self.bundle = [[NSBundle mainBundle]pathForResource:@"datalist" ofType:@"plist" ];//NSString *bundle = [[NSBundle mainBundle] pathForResource:@”data” ofType:@”plist”];
// NSLog(@"%@",_bundle);
//[fileManager copyItemAtPath:_bundle toPath: arr error:&error];
NSMutableArray *valuearray = [[NSMutableArray alloc]initWithContentsOfFile:arr];
if (dict.count)
{
[valuearray addObject:dict];
}
else
{
NSLog(@"data not retrieved");
}
[valuearray writeToFile:arr atomically:YES];
NSLog(@"%@",arr);
//6
}
else
{
NSLog(@"FILE DOESN'T EXIST");
[valuearray writeToFile:arr atomically:YES];
}
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"sucess" message:@"successfully saved" delegate:self cancelButtonTitle:@"ok" otherButtonTitles: nil];
[alert show];
[self.navigationController popToRootViewControllerAnimated:YES];
}
感谢@rmaddy。
关于ios - 每次保存新数据时 Plist 都会重写旧数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34149545/