iOS存储自定义对象模型
2020-03-25 本文已影响0人
Arthur澪
创建一个模型(user)
在.h中。遵守NSCoding
协议
#import <Foundation/Foundation.h>
@interface PDUser : NSObject<NSCoding>
@property(nonatomic,strong)NSString *apiKey;
@property(nonatomic,strong)NSString *apiSecret;
@property(nonatomic,strong)NSString *regDev;
@property(nonatomic,assign)NSInteger user_id;
@end
在.m中。重写方法encodeWithCoder,initWithCoder
#import "PDUser.h"
@implementation PDUser
-(void)encodeWithCoder:(NSCoder *)aCoder{
[aCoder encodeObject:self.apiKey forKey:@"apiKey"];
[aCoder encodeObject:self.apiSecret forKey:@"apiSecret"];
[aCoder encodeObject:self.regDev forKey:@"UUID"];
[aCoder encodeObject:[NSString stringWithFormat:@"%ld",self.user_id] forKey:@"userid"];
}
-(instancetype)initWithCoder:(NSCoder *)aDecoder{
if(self = [super init]){
self.apiKey = [aDecoder decodeObjectForKey:@"apiKey"];
self.apiSecret = [aDecoder decodeObjectForKey:@"apiSecret"];
self.regDev = [aDecoder decodeObjectForKey:@"UUID"];
self.user_id = [[aDecoder decodeObjectForKey:@"userid"] integerValue];
}
return self;
}
外界使用
保存在NSUserDefaults
中,以及从中取出user。
- 保存
//把user对象存入
PDUser *user = [[PDUser alloc] init];
user.apiSecret = _reBackData.apiSecret;
user.apiKey = _reBackData.apiKey;
user.regDev = _reBackData.regDev;
user.user_id = _reBackData.user_id;
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:user];
[[NSUserDefaults standardUserDefaults] setObject:data forKey:@"USERKEY"]; //保存
- 取出
//从中取出user对象
NSUserDefaults *userD = [NSUserDefaults standardUserDefaults];
NSData *data = [userD objectForKey:@"USERKEY"];
PDUser *user = [NSKeyedUnarchiver unarchiveObjectWithData:data];
清除数据
[[NSUserDefaults standardUserDefaults] removeObjectForKey:key];
[[NSUserDefaults standardUserDefaults] synchronize];