1、XML属性列表(plist)归档
plist只能把Fundation框架中的基本数据类型writeToFile,不能存储自定义类
#import "ViewController.h"
@interface ViewController ()
- (IBAction)save;
- (IBAction)read;
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (IBAction)save {
[self saveArray];
}
- (void)saveArray
{
// 1.获得沙盒根路径
NSString *home = NSHomeDirectory();
// 2.document路径
NSString *docPath = [home stringByAppendingPathComponent:@"Documents"];
// 3.新建数据
NSArray *data = @[@"jack", @10, @"ffdsf"];
NSString *filepath = [docPath stringByAppendingPathComponent:@"data.plist"];
[data writeToFile:filepath atomically:YES];
}
- (IBAction)read {
// 1.获得沙盒根路径
NSString *home = NSHomeDirectory();
// 2.document路径
NSString *docPath = [home stringByAppendingPathComponent:@"Documents"];
// 3.文件路径
NSString *filepath = [docPath stringByAppendingPathComponent:@"data.plist"];
// 4.读取数据
NSArray *data = [NSArray arrayWithContentsOfFile:filepath];
NSLog(@"%@", data);
}
@end
xml(.plist)存取和读出的过程如下图所示:
2、Preference(偏好设置)
很多iOS应用都支持偏好设置,比如保存用户名、密码、字体大小等设置,iOS提供了一套标准的解决方案来为应用加入偏好设置功能。每个应用都有个NSUserDefaults实例,通过它来存取偏好设置比如,保存用户名、字体大小、是否自动登录。
#import "ViewController.h"
@interface ViewController ()
- (IBAction)save;
- (IBAction)read;
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)save {
// 1.利用NSUserDefaults,就能直接访问软件的偏好设置(Library/Preferences)
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
// 2.存储数据
[defaults setObject:@"mj" forKey:@"account"];
[defaults setObject:@"123" forKey:@"pwd"];
[defaults setInteger:10 forKey:@"age"];
[defaults setBool:YES forKey:@"auto_login"];
// 3.立刻同步
[defaults synchronize];
/**
注意:UserDefaults设置数据时,不是立即写入,而是根据时间戳定时地把缓存中的数据写入本地磁盘。
所以调用了set方法之后数据有可能还没有写入磁盘应用程序就终止了。
出现以上问题,可以通过调用synchornize方法强制写入。
*/
}
- (IBAction)read {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *account = [defaults objectForKey:@"account"];
BOOL autoLogin = [defaults boolForKey:@"auto_login"];
NSLog(@"%@ -- %d", account, autoLogin);
}
@end