作者:Johnson
链接:https://zhuanlan.zhihu.com/p/379878562
来源:知乎
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
#import "HMPerosn.h"
//
// ViewController.m
// 解档归档复习
//
// Created by lujun on 2021/6/11.
//
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (IBAction)jie:(id)sender {
NSString *path= [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"av1.data"];
NSLog(@"%@",path);
// [NSData dataWithContentsOfFile:path]
HMPerosn *pp=[NSKeyedUnarchiver unarchivedObjectOfClass:[HMPerosn class] fromData:[NSData dataWithContentsOfFile:path] error:nil];
NSLog(@"%@",pp.name);
NSLog(@"%d",pp.age);
}
- (IBAction)gui:(id)sender {
NSLog(@"%@",@"gui");
[self fuJIedangGuidang];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
// [self fuxiplistDeXieRu];
// [self fuxiPianHaoSetting];
}
-(void)fuJIedangGuidang{
NSString *path=[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"av1.data"];
HMPerosn *p1 = [HMPerosn new];
p1.name = @"lili";
p1.age = 22;
NSError *err;
NSData *data=[NSKeyedArchiver archivedDataWithRootObject:p1 requiringSecureCoding:YES error:&err];
[data writeToFile:path atomically:YES];
}
-(void)fuxiPianHaoSetting{
//用户偏好设置,实则还是plist的存储,只是存在沙盒目录下。
///Library/Preferences/com.lujun.------.plist 偏好设置的存储文件的位置
NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
[def setObject:@"lujun" forKey:@"name"];
[def setInteger:25 forKey:@"age"];
[def setBool:YES forKey:@"b1"];
NSLog(@"%@",NSHomeDirectory());
//synchronize 同步的意思
[def synchronize];
}
-(void)fuxiplistDeXieRu{
NSArray *arr = @[@"jack",@"rose",@"lili",@"lujun"];
[arr writeToFile:@"/Users/lujun/Desktop/aa.txt" atomically:YES];
NSDictionary *dict=@{@"name":@"jack",@"age":@(18)};
[dict writeToFile:@"/Users/lujun/Desktop/ab.plist" atomically:YES];
}
@end
模型的头文件
//
// HMPerosn.h
// 解档归档复习
//
// Created by lujun on 2021/6/11.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface HMPerosn : NSObject<NSCoding,NSSecureCoding>
@property(nonatomic,copy)NSString * name;
@property(nonatomic,assign)int age;
@end
NS_ASSUME_NONNULL_END
.m 文件,对协议方法的实现,方法名字记不得的,可以跳到头文件看一下
//
// HMPerosn.m
// 解档归档复习
//
// Created by lujun on 2021/6/11.
//
#import "HMPerosn.h"
@implementation HMPerosn
- (void)encodeWithCoder:(NSCoder *)coder{
[coder encodeObject:self.name forKey:@"name"];
[coder encodeInt:self.age forKey:@"age"];
}
- (instancetype)initWithCoder:(NSCoder *)coder{
if(self=[super init]){
self.name = [coder decodeObjectForKey:@"name"];
self.age = [coder decodeIntForKey:@"age"];
}
return self;
}
+ (BOOL)supportsSecureCoding{
return YES;
}
@end