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文件中写入信息,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];