iOS存储

2019-12-12  本文已影响0人  韡韡_ea9b

解档归档

四个步骤:
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偏好设置

要使用,需要转换为支持的数据类型
例子:
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文件保存

存储:
//获取路径
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数据库

CoreData

iOS CoreData数据库之创建详解

上一篇 下一篇

猜你喜欢

热点阅读