您的位置:首页 > 移动开发 > IOS开发

iOS中plist文件操作

2016-02-17 13:42 537 查看
1、先创建一个plist文件在项目中:

new file - Resource - Property plist - Next(下一步) - 更改名称(chatUserName)- 确认

这样就创建好了一个plist文件

2、获取plist文件路径:

NSString *plistPath = [[NSBundle
mainBundle] pathForResource:@"chatNiceName"
ofType:@"plist"];

3、往plist文件中存入数据:(我这里用的是字典形式,你可以根据需要选择是字典还是数组)

/**

* 往plist文件中写入信息,text作为字典的key 与 value

*/

-(void)writeMsgToPlistFile:(NSString *)text

{

NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES)
objectAtIndex:0]
stringByAppendingPathComponent:@"chatNiceName.plist"];

NSMutableDictionary *dataList = [[[NSMutableDictionary
alloc]
initWithContentsOfFile:path]
mutableCopy];

NSMutableDictionary *dict1 = [NSMutableDictionary
dictionary];

[dict1 setObject:text
forKey:text];

[dataList setObject:dict1
forKey:text];

[dataList writeToFile:path
atomically:YES];

}

plist存入的信息图片展示:



4、读取刚才存在字典里面的信息

/**

* 读取plist文件中写入信息,text作为字典的key 与 value

*/

-(void)getPlistFileAllMsg:(NSString*)text

{

NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES)
objectAtIndex:0]
stringByAppendingPathComponent:@"chatNiceName.plist"];

NSMutableDictionary *dataList = [[[NSMutableDictionary
alloc]
initWithContentsOfFile:path]
mutableCopy];

NSMutableDictionary *dict = [dataList
objectForKey:text];

NSLog(@"%@", dict);

}
打印出来的报文信息



问题:

在论坛上看到有人说往plist文件存入字典信息,会把之前的dict给覆盖掉。这里复原下这种情况代码

如果你取出plist的代码是这样的,那么将会出现覆盖的情况

NSString *plistPath = [[NSBundle
mainBundle] pathForResource:@"chatNiceName"
ofType:@"plist"];

NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: