ios基础之归档和解档
有些api函数已经不在支持了但是我先把之前的api学好,再学后来新出的api函数
系统选取最新的,ios系统也是最新的
//
// Teacher.h
// 22-归档解档
//
// Created by 鲁军 on 2021/2/14.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface Teacher : NSObject <NSCoding>
@property(nonatomic,copy)NSString *name;
@property(nonatomic,assign)int age;
@end
NS_ASSUME_NONNULL_END
//
// Teacher.m
// 22-归档解档
//
// Created by 鲁军 on 2021/2/14.
//
#import "Teacher.h"
@implementation Teacher
- (void)encodeWithCoder:(NSCoder *)coder
{
[coder encodeObject:_name forKey:@"name"];
[coder encodeInt:_age forKey:@"age"];
}
- (instancetype)initWithCoder:(NSCoder *)coder
{
self = [super init];
if (self) {
_name = [coder decodeObjectForKey:@"name"];
_age = [coder decodeIntForKey:@"age"];
}
return self;
}
@end
//
// ViewController.m
// 22-归档解档
//
// Created by 鲁军 on 2021/2/14.
//
#import "ViewController.h"
#import "Teacher.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
[self readData];
}
-(void)writeData{
Teacher *t =[[Teacher alloc] init];
t.name=@"dajun";
t.age=18;
NSString *strTemp =NSTemporaryDirectory();
NSString *filePath = [strTemp stringByAppendingPathComponent:@"te.data"];
//归档
[NSKeyedArchiver archiveRootObject:t toFile:filePath];
NSLog(@"%@",NSHomeDirectory());
}
-(void)readData{
NSString *strTemp =NSTemporaryDirectory();
NSString *filePath = [strTemp stringByAppendingPathComponent:@"te.data"];
//NSKeyedUnarchiver unarchivedObjectWithFile:filePath
Teacher *t = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
NSLog(@"%@====%d",t.name,t.age);
}
@end