plist简单的读写方法

//获取应用程序沙盒的Documents目录(ios程序仅能读取app自己目录内的文件)
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//得到完整的文件名
NSString *plistFilePath = [documentsDirectory stringByAppendingPathComponent:@"cfg.plist"];

另外要注意一点,如果最开始不存在plist文件,则需要手动初始化NSMutableDictionary
NSMutableDictionary* dict = [ [ NSMutableDictionary alloc ] initWithContentsOfFile:CFG_FILE];
if (dict==nil) {
NSArray * key = [[NSArray alloc] initWithObjects:@"shakehandKey",nil];
NSArray * val = [[NSArray alloc] initWithObjects:@"val",nil];
dict = [[ NSMutableDictionary alloc ] initWithObjects:key forKeys:val];
}


[ dict setObject:shakehandKey forKey:@"shakehandKey" ];
代码片段见下:
//读取plist中的数据
-(NSString *)getShakehandkey{
NSMutableDictionary* dict = [ [ NSMutableDictionary alloc ] initWithContentsOfFile:CFG_FILE];
if (dict==nil) {
return nil;
}
NSString* shakehandKey = [ dict objectForKey:@"shakehandKey" ];
return shakehandKey;
}

//保存数据到plist文件中
-(BOOL)saveShakehandkey:(NSString*)shakehandKey{
/*
#define CFG_FILE [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"cfg.plist"]
*/
NSMutableDictionary* dict = [ [ NSMutableDictionary alloc ] initWithContentsOfFile:CFG_FILE];
if (dict==nil) {
NSArray * key = [[NSArray alloc] initWithObjects:@"shakehandKey",nil];
NSArray * val = [[NSArray alloc] initWithObjects:@"val",nil];
dict = [[ NSMutableDictionary alloc ] initWithObjects:key forKeys:val];
}

[ dict setObject:shakehandKey forKey:@"shakehandKey" ];
if (dict==nil) {
NSLog(@"NSMutableDictionary nill 2");
}

NSLog(@"path:%@",CFG_FILE);

return [ dict writeToFile:CFG_FILE atomically:YES ];
}
| 0个评论