NSUserDefaults 用户偏好设定保存自定义类
由于NSUserDefaults 不支持保存自定类,保存的对象需要实现NSCoding协议,不过自定的类型就算实现了NSCoding也不可以保存,可以通过以下方法实现:
//h文件
#import <Foundation/Foundation.h>
@interface UserBean : NSObject<NSCoding>
@property NSInteger userid;
@property(nonatomic,copy)NSString *address;
@property(nonatomic,copy)NSString *levelName;
@property(nonatomic,copy)NSString *mobile;
@property(nonatomic,copy)NSString *telphone;
@property(nonatomic,copy)NSString *userName;
@property(nonatomic,copy)NSString *realName;
@property(nonatomic,copy)NSString *email;
@property NSInteger sex;
@property(nonatomic,copy)NSString *password;
@end
//m文件
#import "UserBean.h"
@implementation UserBean
@synthesize userid,mobile,email,sex,address,password,realName,telphone,userName,levelName;
- (void)encodeWithCoder:(NSCoder *)aCoder{
[aCoder encodeObject:email forKey:@"email"];
[aCoder encodeObject:userName forKey:@"userName"];
[aCoder encodeObject:mobile forKey:@"mobile"];
[aCoder encodeObject:address forKey:@"address"];
[aCoder encodeObject:password forKey:@"password"];
[aCoder encodeObject:realName forKey:@"realName"];
[aCoder encodeObject:telphone forKey:@"telphone"];
[aCoder encodeObject:levelName forKey:@"levelName"];
[aCoder encodeInteger:sex forKey:@"sex"];
[aCoder encodeInteger:userid forKey:@"userid"];
}
- (id)initWithCoder:(NSCoder *)aDecoder{
email= [aDecoder decodeObjectForKey:@"email"] ;
sex= [aDecoder decodeIntegerForKey:@"sex"];
userid= [aDecoder decodeIntegerForKey:@"userid"];
mobile= [aDecoder decodeObjectForKey:@"mobile"];
address= [aDecoder decodeObjectForKey:@"address"];
password= [aDecoder decodeObjectForKey:@"password"];
realName= [aDecoder decodeObjectForKey:@"realName"];
telphone= [aDecoder decodeObjectForKey:@"telphone"];
userName= [aDecoder decodeObjectForKey:@"userName"];
levelName= [aDecoder decodeObjectForKey:@"levelName"];
return self;
}
@end
通过实现
NSKeyedArchiver转换成NSData然后保存到NSUserDefaults中,然后取值的时候可以通过NSKeyedUnarchiver读NSData获得对应的user,代码如下:
NSUserDefaults *nsuser= [NSUserDefaults standardUserDefaults];
UserBean *user = [[UserBean alloc]init];
[user setSex:0];
[user setEmail:@"22222"];
//将对象转化为字节流
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:user];
[nsuser setObject:data forKey:@"userbean"];
//同步
[nsuser synchronize];
//获取字节流
NSData *data_1 =[nsuser objectForKey:@"userbean"];
//解码
UserBean *user1 = [NSKeyedUnarchiver unarchiveObjectWithData:data_1];
NSLog(@"%@",[user1 email]);