废话少说,直接上代码:
(void)viewDidLoad { [super viewDidLoad]; //读取plist文件在程序文件夹中的文件,并且要注意,程序文件的文件只能读不能写,只能在程序沙盒之中; NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"plisttest" ofType:@"plist"]; NSLog(@"这是plist文件的路径%@", plistPath); NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath]; NSLog(@"这是plist文件的内容%@", data); //添加数据说明,可以进行修改; [data setObject:@"我在东北大学" forKey:@"address"]; [data setObject:@"男" forKey:@"sex"]; //获取应用沙盒的的DOCUMENT 的路径; NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString* plistPath1 = [paths objectAtIndex:0]; //在此处设置文件的名字补全其中的路径, 注意对于文件内存的修改是在内存之中完成的,然后直接把现在的数据一次性更新,这样减少了文件的读写的次数 NSString *filename =[plistPath1 stringByAppendingPathComponent:@"plisttest.plist"]; NSLog(@"这是沙盒之中的路径%@", filename); //写入文件 [data writeToFile:filename atomically:YES]; NSLog(@"证明我的数据真正得写入在其中了"); //证明文件写入成功 NSMutableDictionary *afterData = [[NSMutableDictionary alloc] initWithContentsOfFile:filename]; NSLog(@"这是写入过数据的情况%@", afterData); NSLog(@"程序结束"); // Do any additional setup after loading the view, typically from a nib. }
运行结果是:
2015-04-26 12:08:55.857 plist[1702:112934] 这是plist文件的路径/Users/xuyaowen/Library/Developer/CoreSimulator/Devices/6BD2A547-CC45-4739-9578-C1D268C26B20/data/Containers/Bundle/Application/28977EA1-0F6A-4B4F-AF37-F6BADEEB889C/plist.app/plisttest.plist 2015-04-26 12:08:55.868 plist[1702:112934] 这是plist文件的内容{ info = "\U8fd9\U662f\U6211\U7684plist\U6587\U4ef6"; name = xiaohongqi; password = xiaohongqi; } 2015-04-26 12:08:55.869 plist[1702:112934] 这是沙盒之中的路径/Users/xuyaowen/Library/Developer/CoreSimulator/Devices/6BD2A547-CC45-4739-9578-C1D268C26B20/data/Containers/Data/Application/F145B509-73B0-4266-AE06-94F2B0A56A7C/Documents/plisttest.plist 2015-04-26 12:08:55.902 plist[1702:112934] 证明我的数据真正得写入在其中了 2015-04-26 12:08:55.902 plist[1702:112934] 这是写入过数据的情况{ address = "\U6211\U5728\U4e1c\U5317\U5927\U5b66"; info = "\U8fd9\U662f\U6211\U7684plist\U6587\U4ef6"; name = xiaohongqi; password = xiaohongqi; sex = "\U7537"; } 2015-04-26 12:08:55.902 plist[1702:112934] 程序结束
然后通过运行结束时的日志内容,证明成功!
用前往文件夹:复制路径即可访问到程序沙盒之中的文件,注意提高自身的能力!
时间: 2024-10-04 14:22:03