iOS --归档存储自定义对象
#import <Foundation/Foundation.h> @interface User : NSObject<NSCoding> //遵循NSCoding协议 /** name */ @property (nonatomic, copy) NSString *name; /** age */ @property (nonatomic, assign) NSInteger age; //自定义初始化方法 - (instancetype)initWithName:(NSString *)name age:(NSInteger)age; @end ----------- #import "User.h" @implementation User //初始化 - (instancetype)initWithName:(NSString *)name age:(NSInteger)age { self = [super init]; if (self) { self.name = name; self.age = age; } return self; } //归档 - (void)encodeWithCoder:(NSCoder *)aCoder { [aCoder encodeObject:self.name forKey:@"name"]; [aCoder encodeInteger:self.age forKey:@"age"]; } //反归档 - (instancetype)initWithCoder:(NSCoder *)aDecoder { self = [super init]; if (self) { self.name = [aDecoder decodeObjectForKey:@"name"]; self.age = [aDecoder decodeIntegerForKey:@"age"]; } return self; } @end
//归档 编码 User *user = [[User alloc] initWithName:@"张三" age:18]; NSData *userData = [NSKeyedArchiver archivedDataWithRootObject:user]; //反归档 解码 User *user1 = [NSKeyedUnarchiver unarchiveObjectWithData:userData];