iOS应用数据存储的方式
1、XML属性列表(plist)归档
2、preference(偏好设置)
3、NSKeyedArchiver归档(NSCoding)
4、SQLite3
5、Core Data
1、plist文件存储-(沙盒存储)
注意:不可以存储自定义对象,一个对象能不能使用plist存储,可以通过看他有没有write to file方法
存入:
// 获取沙盒路径
NSString *cachePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
// 拼写全路径
NSString *filePath =[cachePath stringByAppendingPathComponent:@"arr.plist"];
NSArray *arr = @[@"sign",@10];
[arr writeToFile:filePath atomically:YES];
NSLog(@"%@",cachePath);
读取
// 获取沙盒路径
NSString *cachepath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
// 拼写全路径
NSString *filepath = [cachepath stringByAppendingPathComponent:@"arr.plist"];
// 读取
NSArray *arr = [NSArray arrayWithContentsOfFile:filepath];
NSLog(@"%@", arr);
2、偏好设置-(沙盒存储)
** 1.不需要关心文件名**
** 2.快速做键值对存储**
** 3.基本数据类型都可以存储**
存储
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:@"sun" forKey:@"name"];
[defaults setObject:@"49" forKey:@"age"];
// iOS7之前不会马上同步,所以适配iOS7之前的时候要加
[defaults synchronize];
读取:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *str = [defaults objectForKey:@"name"];
NSLog(@"%@", str);
3、归档-(沙盒存储)
可以存储自定义对象
这里介绍自定义一个person对象<遵守NSCoding协议>
实现这份协议里面的方法让自定义对象里面的属性可以存储
@interface Person : NSObject<NSCoding>
@property (nonatomic, strong)NSString *name;
// 协议里面的方法:
- (void)encodeWithCoder:(NSCoder *)aCoder; // 归档
- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder; // 解档
// 存储name属性
- (void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeObject:_name forKey:@"name"];
}
// 读取name属性并赋值
- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
if (self = [super init]) {
_name = [aDecoder decodeObjectForKey:@"name"];
}
return self;
}
归档:(前提必须实现encodeWithCoder:方法)
Person * p = [[Person alloc] init];
p.name = @"siog";
NSString *cachepath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
NSString *filePath = [cachepath stringByAppendingPathComponent:@"person.data"];
[NSKeyedArchiver archiveRootObject:p toFile:filePath];
解档:(必须实现initWithCoder:)
NSString *cachepath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
NSString *filePath = [cachepath stringByAppendingPathComponent:@"person.data"];
Person *p = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
NSLog(@"%@", p.name);
4、SQLite3
5、CoreData