最近在做一个仿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(@"文件删除成功");
}