界面图:
NSDocumentDirectory表示的目录图片:
NSCachesDirectory表示的目录图片:
//NSHomeDirectory()获取沙盒根目录
//NSLog(@"%@",NSHomeDirectory());
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//NSHomeDirectory()获取沙盒根目录
//NSLog(@"%@",NSHomeDirectory());
//获取指定的目录
NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSLog(@"%@",path);
}
// plist存储
// 保存到plist
- (IBAction)save:(id)sender {
// 获取指定的目录
// NSUserDomainMask,默认手机开发的话,就填该参数
// YES是表示详细目录,如果填NO的话,那么前面的目录默认会用~表示,这个~在电脑可以识别,在手机里面是不能识别的,所以默认也用YES
NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSArray *array = @[@"xmg",@10];
// 拼接路径名称
//NSString *filePath = [path stringByAppendingString:@"array.plist"];
NSString *filePath = [path stringByAppendingPathComponent:@"array.plist"];
NSLog(@"%@",filePath);
//把数组写入到文件
[array writeToFile:filePath atomically:YES];
//把字典写入到文件
NSDictionary *dict = @{@"name" : @"xmg",@"age" : @10};
NSString *dictFilePath = [path stringByAppendingPathComponent:@"dict.plist"];
[dict writeToFile:dictFilePath atomically:YES];
}
// 从plist中加载
- (IBAction)read:(id)sender {
//获取指定的目录
NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *filePath = [path stringByAppendingPathComponent:@"array.plist"];
NSString *dictFilePath = [path stringByAppendingPathComponent:@"dict.plist"];
NSArray *array = [NSArray arrayWithContentsOfFile:filePath];
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:dictFilePath];
NSLog(@"%@",array);
NSLog(@"%@",dict);
}
@end
程序运行前:沙盒根目录图片:
程序运行后,点击保存按钮效果图片:
程序运行后,点击读取按钮效果图片:
- 注意,plist方式存储和偏好设置方式存储不能存放自定义对象要想,存放自定义对象,可以通过归档方式存储