首页 > 代码库 > NSUserDefault 保存自定义对象

NSUserDefault 保存自定义对象

由于NSUserDefaults 不支持保存自定类,保存的对象需要实现NSCoding协议,不过自定的类型就算实现了NSCoding也不可以保存,可以通过以下方法实现:

//h文件
#import <Foundation/Foundation.h>

@interface People : NSObject<NSCoding>

@property(nonatomic,copy)NSString *name;
@property(nonatomic,copy)NSString *age;

@end

//m文件

#import "People.h"

@implementation People

- (void)encodeWithCoder:(NSCoder *)aCoder{
    [aCoder encodeObject:_name forKey:@"name"];
    [aCoder encodeObject:_age forKey:@"age"];
    
}
- (id)initWithCoder:(NSCoder *)aDecoder{
    _name= [aDecoder decodeObjectForKey:@"name"] ;
    _age= [aDecoder decodeIntegerForKey:@"age"];
    return self;
}
@end

 

 

通过实现

NSKeyedArchiver转换成NSData然后保存到NSUserDefaults中,然后取值的时候可以通过NSKeyedUnarchiver读NSData获得对应的user,代码如下:

NSUserDefaults *userDefault= [NSUserDefaults standardUserDefaults];
    People *p = [[People alloc]init];
     p.name = @"张飞";
    p.age = @"32";
    //将对象转化为字节流
    NSData *data =http://www.mamicode.com/ [NSKeyedArchiver archivedDataWithRootObject: p];
    
    [userDefault setObject:data forKey:@"user"];
    //同步
    [nsuser synchronize];

    //获取
    NSData *getdata =http://www.mamicode.com/[nsuser objectForKey:@"user"];
    //解码
    People *getP = [NSKeyedUnarchiver unarchiveObjectWithData:getdata];
  
    
    NSLog(@"%@",getP.name);