plist文件是将某些特定的类,通过XML文件的方式保存在目录中。
可以被序列化的类型只有如下几种:
1
2
3
4
5
6
7
8
9
10
|
NSArray; NSMutableArray; NSDictionary; NSMutableDictionary; NSData; NSMutableData; NSString; NSMutableString; NSNumber; NSDate; |
1.获得文件路径
1
2
|
NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject; NSString *fileName = [path stringByAppendingPathComponent:@ "123.plist" ]; |
2.存储
1
2
|
NSArray *array = @[@ "123" , @ "456" , @ "789" ]; [array writeToFile:fileName atomically:YES]; |
3.读取
1
2
|
NSArray *result = [NSArray arrayWithContentsOfFile:fileName]; NSLog(@ "%@" , result); |
4.注意
-
只有以上列出的类型才能使用plist文件存储。
-
存储时使用writeToFile: atomically:方法。 其中atomically表示是否需要先写入一个辅助文件,再把辅助文件拷贝到目标文件地址。这是更安全的写入文件方法,一般都写YES。
-
读取时使用arrayWithContentsOfFile:方法。