plist文件读写

最近在做一个仿qq的聊天功能,然后里面需要用到plist文件来储存相关的一些应用信息,比如说一些登陆信息的用户名和密码之类,这次就介绍几种plist文件读写的相关方法。
读取文件:

- (void)viewDidLoad  
{  
    [super viewDidLoad];  
    //读取plist  
    NSString *Path = [[NSBundle mainBundle] pathForResource:@"message" ofType:@"plist"];  
    NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile:Path];  
    //把plist文件中的所有数据直接打印出来
    NSLog(@"%@", data);  
}  

文件添加:
上面是应用程序中添加文件,这个时候可以选择代码在沙盒中添加。

NSArray * messagepath= NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  //获取完整路径
  NSString *documentsDirectory = [messagepath objectAtIndex:0];
  NSString *tPath = [documentsDirectory stringByAppendingPathComponent:@"message.plist"];
  //存储根数据
  NSMutableDictionary *rootDic = [[NSMutableDictionary alloc ] init];
  //读取详细数据
  NSMutableDictionary *friendDic = [[NSMutableDictionary alloc]init];
  [friendDic setObject:@"Daylly" forKey:@"UserName"];
  [rootDic setObject:userDataDic forKey:@"Login"];
  //写入文件
  [rootDic writeToFile:Path atomically:YES];
  NSLog(@"%@",NSHomeDirectory());

读取数据:

//获取路径
  NSArray *path= NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  NSString *filePath = [[path objectAtIndex:0] stringByAppendingPathComponent:@"message.plist"];
  NSLog(@"%@",NSHomeDirectory());
  //获取数据
  NSMutableDictionary *searchdata = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
  NSLog(@"%@",searchdata);

对数据进行修改,删除:

    NSMutableDictionary *msg = [dataDictionary objectForKey:@"text"];
    [msg setObject:@"你好" forKey:@"message"];
    [msg setObject:@"0" forKey:@"type"];
    [msg removeObjectForKey:@"text"];

    //修改成功以后,将小字典重新添加到大字典里面
    [dataDictionary setObject:msg forKey:@"text"];

    [dataDictionary writeToFile:filePatch atomically:YES];
    NSLog(@"%@",dataDictionary);

文件的删除:

NSFileManager *manager=[NSFileManager defaultManager];
    //文件路径
      NSString *filepath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:@"sandbox.plist"];
    if ([manager removeItemAtPath:filepath error:nil]) {
        NSLog(@"文件删除成功");
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值