这篇文章是自己通过实践获取,在网上查过很多资料,也走了不上的弯路,由于刚开始学子不久,只是把自己遇到的问题贡献给大家
一,创建文件
//获取路径对象
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//获取完整路径
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *plistPath = [documentsDirectory stringByAppendingPathComponent:@"test.plist"];
NSMutableDictionary *dictplist = [[NSMutableDictionary alloc ] init];
//设置属性值
[dictplist setObject:@"张三" forKey:@"name"];
[dictplist setObject:@"李四" forKey:@"name1"];
[dictplist setObject:@"王五" forKey:@"name2"];
//写入文件
[dictplist writeToFile:plistPath atomically:YES];
这个是创建了一个简单的plist文件,创建后的图1为:
下面是创建了一种多键值的plist文件,代码和图如下:
//获取路径对象
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//获取完整路径
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *plistPath = [documentsDirectory stringByAppendingPathComponent:@"test.plist"];
NSMutableDictionary *dictplist = [[NSMutableDictionary alloc ] init];
//定义第一个插件的属性
NSMutableDictionary *plugin1 = [[NSMutableDictionary alloc]init];
[plugin1 setObject:@"张三" forKey:@"name1"];
[plugin1 setObject:@"李四" forKey:@"name2"];
//定义第二个插件的属性
NSMutableDictionary *plugin2 = [[NSMutableDictionary alloc]init];
[plugin2 setObject:@"王五" forKey:@"name1"];
[plugin2 setObject:@"赵斌" forKey:@"name2"];
//设置属性值
[dictplist setObject:plugin1 forKey:@"初一班"];
[dictplist setObject:plugin2 forKey:@"初二班"];
//写入文件
[dictplist writeToFile:plistPath atomically:YES];
图2:
针对图1进行修改的程序,代码如下:
NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]stringByAppendingPathComponent:@"test.plist"];
NSMutableDictionary *applist = [[[NSMutableDictionary alloc]initWithContentsOfFile:path]mutableCopy];
NSString *name = [applist objectForKey:@"name"];
name = @"山山";
[applist setObject:name forKey:@"name"];
[applist writeToFile:path atomically:YES];
执行后如下图:
针对图2进行修改的程序,代码如下:
[dictplist writeToFile:plistPath atomically:YES];
NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:@"test.plist"];
//根据路径获取test.plist的全部内容
NSMutableDictionary *infolist= [[[NSMutableDictionary alloc]initWithContentsOfFile:path]mutableCopy];
//获取初一班的信息
NSMutableDictionary *info = [infolist objectForKey:@"初一班"];
NSString *name1 = [info objectForKey:@"name1"];
name1 = @"山山";
[info setValue:name1 forKey:@"name1"];
[infolist setValue:info forKey:@"初一班"];
[infolist writeToFile:path atomically:YES];
图如下:
以上两个修改信息的地方,必须要加入红色标记的方法,才能在表里进行增改操作。
以上是个人的学习心得,请大家多多指教。