属性列表文件是一种XML文件,Foundation框架中的数组和字典等均可以于属性列表文件相互转换。数组
NSArray类经常使用读写属性列表文件的方法:app
+arrayWithContentsOfFile:类级构造方法,用于从属性列表文件中读取数据,建立NSArray对象。框架
-initWithContentsOfFile:实例构造方法,用于从属性列表文件中读取数据,建立NSArray对象。atom
-writeToFile:atomically:该方法把NSArray对象写入到属性列表文件中,第一个参数是文件名,第二个参数为是否使用辅助文件,若是为YES,则先写入到一个辅助文件,而后辅助文件再从新命名为目标文件,若是为NO,则直接写入到目标文件。spa
NSDictionary类经常使用读写属性列表文件的方法:code
+dictionaryWithContentsOfFile:类级构造方法,用于从属性列表文件中读取数据,建立NSDictionary对象。对象
-initWithContentsOfFile:实例构造方法,用于从属性列表文件中读取数据,建立NSDictionary对象。blog
-writeToFile:atomically:该方法将NSDictionary对象写入到属性列表文件中。ip
属性列表文件数据持久化具体方法,可参考如下实现方式:资源
假如在项目中手工建立了一个Contacts.plist文件,并在该文件中添加了几条数据,以下图所示。
固然也能够经过代码直接建立plist文件。
接下来须要作的是将项目资源的Contacts.plist文件中数据复制到沙箱Documents目录下。
//对文件进行预处理,判断在Documents目录下是否存在plist文件,若是不存在则从资源目录下复制一个。 -(void)createEditableCopyOfDatabaseIfNeeded { NSFileManager *fileManager=[NSFileManager defaultManager]; NSString *writableDBPath=[self applicationDocumentsDirectoryFile]; BOOL dbexits=[fileManager fileExistsAtPath:writableDBPath]; if (!dbexits) { NSString *defaultDBPath=[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Contacts.plist"]; NSError *error; BOOL success=[fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error]; if (!success) { NSAssert1(0,@"错误写入文件:‘%@’",[error localizedDescription]); } } } //获取放置在沙箱Documents目录下的文件的完整路径 -(NSString *)applicationDocumentsDirectoryFile { NSString *documentDirectory=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; NSString *path=[documentDirectory stringByAppendingPathComponent:@"Contacts.plist"]; return path; }
createEditableCopyOfDatabaseIfNeeded方法中:
NSFileManager的copyItemAtPath:toPath:error:方法实现文件复制。
NSAssert1是Foundation框架提供的宏,它在断言失败的状况下抛出异常,相似的还有NSAssert和NSAssert2等。
applicationDocumentsDirectoryFile方法中:
stringByAppendingPathComponent:可以在目录后面追加文件名,返回完整的文件路径。
沙箱Documents目录下成功生成plist文件以后,就能够进行增、删、改、查操做了。可参考以下代码:
NSString *path=[self applicationDocumentsDirectoryFile]; //将属性列表文件内容读取到array变量中,也就是获取了属性列表文件中所有的数据集合 NSMutableArray *array=[[NSMutableArray alloc]initWithContentsOfFile:path]; //向array中添加一条新记录 NSDictionary *newContact=[NSDictionary dictionaryWithObjects:@[contact.Title,contact.Type] forKeys:@[@"Title",@"Type"]]; [array addObject:newContact]; //删除array中一条记录 [array removeObjectAtIndex:0]; //删除array中所有记录 [array removeAllObjects]; for (NSDictionary* dict in array) { //经过for循环,找到须要修改的数据项,进行修改数据 [dict setValue:@"Test" forKey:@"Title"]; } //将array从新写入属性列表文件中 [array writeToFile:path atomically:YES];
注:完成后,须要选择Product->Clean菜单项清除一些再编译。