初级数据持久化NSKeyedArchiver(二)
看代码:
1 #import "MainViewController.h" 2 #import "Student.h" 3 4 @interface MainViewController () 5 6 @end 7 8 @implementation MainViewController 9 10 - (void)viewDidLoad { 11 [super viewDidLoad]; 12 // Do any additional setup after loading the view. 13 14 15 Student *student = [[Student alloc]initWithName:@"安妮" Sex:@"女" HP:1800]; 16 17 18 19 20 21 #pragma mark --归档(序列化) 22 23 //归档 24 //1.创建NSMUTableData 25 NSMutableData *data = [NSMutableData data]; 26 27 //2.创建一个归档对象 28 NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:data]; 29 30 //3.用归档对象将自定义类的对象转化成二进制数据流(NSData) 31 [archiver encodeObject:student forKey:@"student"]; 32 33 //4.归档完成 34 [archiver finishEncoding]; 35 36 //5.归档完成之后写入本地 37 38 NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; 39 40 // //直接写入路劲 41 // [NSKeyedArchiver archiveRootObject:student toFile:[documentsPath stringByAppendingPathComponent:@"student.mp3"]]; 42 43 NSString *studentPath = [documentsPath stringByAppendingPathComponent:@"student.txt"]; 44 45 [data writeToFile:studentPath atomically:YES]; 46 47 NSLog(@"%@",studentPath); 48 49 50 51 52 53 54 #pragma mark --反归档(反序列化) 55 56 //1.获取存进去的二进制文件 57 NSMutableData *unData = [[NSMutableData alloc]initWithContentsOfFile:studentPath]; 58 59 //2.创建反归档对象 60 NSKeyedUnarchiver *unArchiver = [[NSKeyedUnarchiver alloc]initForReadingWithData:unData]; 61 62 //3.将二进制文件转化为OC对象 63 64 Student *stu = [unArchiver decodeObjectForKey:@"student"]; 65 66 NSLog(@"%@",stu.name); 67 68 [unArchiver finishDecoding]; 69 70 71 }
model类里面怎么写了?继续看下去
1 #import <Foundation/Foundation.h> 2 3 //必须签订协议 4 @interface Student : NSObject<NSCoding> 5 6 @property (nonatomic,retain) NSString *name ; 7 8 @property (nonatomic,retain) NSString *sex ; 9 10 @property (nonatomic,assign) int HP ; 11 12 -(instancetype)initWithName:(NSString *)name Sex:(NSString *)sex HP:(int)HP ; 13 14 15 ********************************************** 16 17 #import "Student.h" 18 19 @implementation Student 20 21 -(void)dealloc{ 22 [_name release]; 23 [_sex release]; 24 [super dealloc]; 25 } 26 27 28 #pragma mark --解压过程 29 -(id)initWithCoder:(NSCoder *)aDecoder{ 30 self = [super init] ; 31 if (self) { 32 self.name = [aDecoder decodeObjectForKey:@"name"]; 33 self.sex = [aDecoder decodeObjectForKey:@"sex"] ; 34 self.HP = [aDecoder decodeIntForKey:@"HP"] ; 35 } 36 37 38 return self ; 39 } 40 41 #pragma mark --压缩过程 42 -(void)encodeWithCoder:(NSCoder *)aCoder{ 43 44 //转化的是自身的属性,压缩过程 45 [aCoder encodeObject:self.name forKey:@"name"] ; 46 [aCoder encodeObject:self.sex forKey:@"sex"] ; 47 [aCoder encodeInt:self.HP forKey:@"HP"] ; 48 49 50 } 51 52 53 54 55 -(instancetype)initWithName:(NSString *)name Sex:(NSString *)sex HP:(int)HP{ 56 57 if (self = [super init]) { 58 self.name = name ; 59 self.sex = sex ; 60 self.HP = HP ; 61 } 62 63 return self ; 64 65 66 }