iOS自定义对象存储,必须继承NSCoding
协议,实现对应的- (void)encodeWithCoder:(NSCoder *)coder;
和- (nullable instancetype)initWithCoder:(NSCoder *)coder;
方法
RGArchiver
采用runtime
运行时特性,自动给对象添加encodeWithCoder
,initWithCoder
方法,在对应的方法中获取对象所有成员变量,进行持久化存储
使用 pod 'RGArchiver'
下载框架即可直接使用,如果pod失败,需要先执行pod repo update
更新本地pod库
示例
#import <Foundation/Foundation.h>
@interface User : NSObject
@property(nonatomic,assign) NSInteger age;
@property(nonatomic,copy) NSString *name;
@property(nonatomic,copy) NSString *address;
@end
@implementation User
@end
- (IBAction)archiverUser:(id)sender {
User *user = [User new];
user.name = @"小明";
user.age = 17;
[RGArchiver archiverObject:user toFile:[self userPath]];
}
- (IBAction)unarchiverUser:(id)sender {
User *user = [RGArchiver unArchiverObjectOfObjectClass:[User class] fromFile:[self userPath]];
NSLog(@"age = %ld,name = %@",user.age,user.name);
}
- (NSString *)userPath {
NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"user.plist"];
NSLog(@"userPath = %@",path);
return path;
}
User中类并没有实现NSCoding
协议,即可实现User对象的存储
网友评论