iOS 对plist文件进行读写,增删改查的实例

对plist文件进行读写

//获取路径对象 
  NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
  NSString *path = [pathArray objectAtIndex:0]; 
  //获取文件的完整路径 
  NSString *filePatch = [path stringByAppendingPathComponent:@"column.plist"]; 
   
  NSLog(@"%@",filePatch); 
   
  //写入数据到plist文件 
  NSMutableDictionary *dic1 = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"小小虎",@"name",@"5",@"age",@"boy",@"sex",nil]; 
   
  NSMutableDictionary *dic2 = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"小小兮",@"name",@"6",@"age",@"girl",@"sex",nil]; 
   
  //将上面2个小字典保存到大字典里面 
  NSMutableDictionary *dataDic = [NSMutableDictionary dictionary]; 
  [dataDic setObject:dic1 forKey:@"一年级"]; 
  [dataDic setObject:dic2 forKey:@"二年级"]; 
  //写入plist里面 
  [dataDic writeToFile:filePatch atomically:YES]; 
   
   
  //读取plist文件的内容 
  NSMutableDictionary *dataDictionary = [[NSMutableDictionary alloc] initWithContentsOfFile:filePatch]; 
  NSLog(@"---plist一开始保存时候的内容---%@",dataDictionary); 

对pilst文件进行修改

//修改字典里面的内容,先按照结构取到你想修改内容的小字典 
  NSMutableDictionary *dd = [dataDictionary objectForKey:@"一年级"]; 
  [dd setObject:@"我改名字了哦" forKey:@"name"]; 
  [dd setObject:@"我添加的新内容" forKey:@"content"]; 
  [dd removeObjectForKey:@"age"]; 
   
  //修改成功以后,将这个小字典重新添加到大字典里面 
  [dataDictionary setObject:dd forKey:@"一年级"]; 
   
  [dataDictionary writeToFile:filePatch atomically:YES]; 
  NSLog(@"---plist做过操作之后的字典里面内容---%@",dataDictionary); 

删除

//清除plist文件,可以根据我上面讲的方式进去本地查看plist文件是否被清除 
  NSFileManager *fileMger = [NSFileManager defaultManager]; 
    
  NSString *xiaoXiPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:@"xiaoxi.plist"]; 
    
  //如果文件路径存在的话 
  BOOL bRet = [fileMger fileExistsAtPath:xiaoXiPath]; 
    
  if (bRet) { 
      
    NSError *err; 
      
    [fileMger removeItemAtPath:xiaoXiPath error:&err]; 
  } 

以上这篇iOS 对plist文件进行读写,增删改查的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持呐喊教程。

声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#nhooo.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。