iOS NSUserDefaults 存储(一)

1.NSUserDefaults 介绍

  • 作用就是数据持久化,NSUserDefaults 数据存放在沙盒 Library/Preferences/ 目录下 的 .plist文件
  • 是一个单例,整个程序只有一个实例对象,主要面向的是一些简单数据类型,如:NSNumber、NSString、NSArray、NSDictionary NSDate...

EG:简单使用

存:

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *password = @"123456";
[defaults setObject:password forKey:@"userPassword"];

取:

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *password = [defaults objectForKey:@"userPassword"];

删除:

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults removeObjectForKey:@"userPassword"];

2.使用注意

  • NSUserDefaults存储的对象最好不可变的,想存可变的也可以,那你很6哦,随便你。
  • 对于可变数组和字典 存的时候转为不可变的再存。
  • 取的时候用可变的数组或者字典接收

以数组为例:字典同理

存:

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSMutableArray *mutableArr = [NSMutableArray arrayWithObjects:@"1",@"2",@"3", nil];
NSArray *arr = [NSArray arrayWithArray:mutableArr];
[defaults setObject:arr forKey:@"mutableArr"];//这里最好存放不可变的(arr

取:

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSMutableArray *mutableArr = [NSMutableArray arrayWithArray:[defaults objectForKey:@"mutableArr"]];

3.使用NSUserDefauls 存自定义对象Eg:(model,arrayModels)

model 需要序列化 实现NSCoding中的协议

  • dyIconModel.h
@interface dyIconModel : NSObject

@property (nonatomic, copy) NSString *type;
@property (nonatomic, copy) NSString *ctype;
/**"找经纪人*/
@property (nonatomic, copy) NSString *cname;
/**图标地址*/
@property (nonatomic, copy) NSString *url;
@end
  • dyIconModel.m
//需要实现NSCoding中的协议的两个方法
- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
    if (self == [super init]) {
        self.type = [aDecoder decodeObjectForKey:@"type"];
        self.ctype = [aDecoder decodeObjectForKey:@"ctype"];
        self.cname = [aDecoder decodeObjectForKey:@"cname"];
        self.url = [aDecoder decodeObjectForKey:@"url"];
        
    }
    return self;
}

- (void)encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeObject:self.type forKey:@"type"];
     [aCoder encodeObject:self.ctype forKey:@"ctype"];
     [aCoder encodeObject:self.cname forKey:@"cname"];
     [aCoder encodeObject:self.url forKey:@"url"];
}

归档解档 存取

//self.homeIconArray model 数组
  NSArray *homeIcons = [NSArray arrayWithArray:self.homeIconArray];

  //归档
   NSData * wData = [NSKeyedArchiver archivedDataWithRootObject:homeIcons];

  //存NSUserDefault
    [[NSUserDefaults standardUserDefaults] setObject:wData forKey:homeIconKey];


  //取
 NSData * rData = [[NSUserDefaults standardUserDefaults] objectForKey:homeIconKey];

  //解档
 NSMutableArray *muarray =   [NSMutableArray arrayWithArray:[NSKeyedUnarchiver unarchiveObjectWithData:rData]];
  

删除NSUserDefaults 数据

你可能感兴趣的:(iOS NSUserDefaults 存储(一))