#import <Foundation/Foundation.h>
#import "Student.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
Student *student = [[Student alloc] init];
student.name = @"lili";
student.code = @"123456789";
student.age = 11;
//通过归档将自定义对象的数据转换成NSData
NSData *studentData = [NSKeyedArchiver archivedDataWithRootObject:student ];
//将NSData存入沙盒
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:studentData forKey:@"studentInformation"];
//取出数据
NSData *data = [defaults objectForKey:@"studentInformation"];
//解档
Student *student1 = [NSKeyedUnarchiver unarchiveObjectWithData:data];
NSLog(@"student1 = %@",student1);
}
return 0;
}
Student.h文件
#import <Foundation/Foundation.h>
@interface Student : NSObject<NSCoding>
@property (nonatomic, copy)NSString *name;//姓名
@property (nonatomic, copy)NSString *code;
@property (nonatomic, assign)NSInteger age;
@end
Student.m文件
#import "Student.h"
@implementation Student
//以下两个方法是协议的方法,因为遵守了NSCoding协议,必须实现他的协议方法
//转换为NSData----
//重写encodeWithCoder
- (void)encodeWithCoder:(NSCoder *)aCoder{
NSNumber *age = @(self.age);
[aCoder encodeObject:self.name forKey:@"name"];
[aCoder encodeObject:self.code forKey:@"code"];
[aCoder encodeObject:age forKey:@"age"];
}
//重写init
- (instancetype)initWithCoder:(NSCoder *)coder
{
self = [super init];
if (self) {
self.name = [coder decodeObjectForKey:@"name"];
self.code = [coder decodeObjectForKey:@"code"];
self.age = [[coder decodeObjectForKey:@"age"] integerValue];
}
return self;
}
@end