解档归档
- 需要遵守NScoding协议
- 优点:存储自定义数据对象
- 缺点:只能一次性归档保存以及一次性解压。
- 所以针对小量数据,且对数据操作笨拙,如果向改动数据的一小部分,需要解压整个归档数据
四个步骤:
1.遵守NSCoding协议
2.实现协议对应方法,encodeWithCoder和initWithCoder方法
3.归档方法
4.解档方法
1.
@interface Person : NSObject<NSCoding>
2.
- (void)encodeWithCoder:(nonnull NSCoder *)aCoder {
[aCoder encodeObject:self.name forKey:@"name"];
[aCoder encodeObject:self.age forKey:@"sex"];
}
- (nullable instancetype)initWithCoder:(nonnull NSCoder *)aDecoder {
self = [super init];
if (self) {
self.name = [aDecoder decodeObjectForKey:@"name"];
self.age = [aDecoder decodeObjectForKey:@"sex"];
}
return self;
}
3.
Person *person = [[Person alloc]init];
person.name = @"abc";
person.sex = @"aa";
//归档
NSString *path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
NSString *filePath = [path stringByAppendingPathComponent:@"person.data"];
[NSKeyedArchiver archiveRootObject:person toFile:filePath];
4.
NSString *path1 = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
NSString *filePath1 = [path1 stringByAppendingPathComponent:@"person.data"];
Person *person1 = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath1];
NSLog(@"%@---%@",person1.name,person1.sex);
NSUserDefaults偏好设置
- 是一个单例对象,保存的数据类型有,基本数据类型和NSNumber、NSString、NSData、NSArray、NSDictionary、NSURL
- 优点:
- 缺点:
要使用,需要转换为支持的数据类型
例子:
NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
UIImage *image=[[UIImage alloc]initWithContentsOfFile:@"photo.jpg"];
NSData *imageData = UIImageJPEGRepresentation(image, 100);//UIImage对象转换成NSData
[defaults setObject: imageData forKey:@"image"];
[defaults synchronize];//立即保存
读取:
NSString *username = [defaults objectForKey:kUsernameKey];
删除:
[defaults removeObjectForKey:(nonnull NSString *)];
plist文件保存
- plist本身就是XML文件,名字后缀为.plist
- plist主要保存的数据类型为NSString、NSNumber、NSArray、NSDictionary
存储:
//获取路径
NSString *cachePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject;
NSString *filePath = [cachePath stringByAppendingPathComponent:@"testPlist.plist"];
//生成字典
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setObject:@"ran" forKey:@"name"];
[dict setObject:@"18" forKey:@"age"];
//存储:
[dict writeToFile:filePath atomically:YES];
取出:
NSDictionary *t = [NSDictionary dictionaryWithContentsOfFile:filePath];//filePath为路径
SQLite数据库
- FMDB
- 优点:对libsqlite3的封装,使用简洁,更加面向对象。对于多线程的并发进行了处理,是线程安全的
- 缺点:对于OC语言的封装,只能在iOS开发中使用,跨平台存在局限性
iOS FMDB库详解
CoreData
iOS CoreData数据库之创建详解
网友评论