NSUserDefault用法

方法很简单,一行代码就可以搞定

//保存
- (void)saveValue:(NSString *)value forKey:(NSString *)key
{
    [[NSUserDefaults standardUserDefaults] setObject:value forKey:key];
}

//读取
- (void)readValueforKey:(NSString *)key
{
    [[NSUserDefaults standardUserDefaults] objectForKey:key];
}

注意

  1. NSUserDefault只能保存特定类型的对象:NSData, NSString, NSNumber, NSDate, NSArray, NSDictionary。如果想要存储其它类型,需要将打包成NSData类型。
  2. 如果保存其他类型的对象,会报错

    [User Defaults] Attempt to set a non-property-list object as an NSUserDefaults/CFPreferences value for key str

自定义Model打包NSData类型

  1. 新建一个类Model,实现NSCoding协议
    Model.h
    #import 
    
    @interface Model : NSObject
    
    @property (nonatomic, copy) NSString *name;
    @property (nonatomic, copy) NSString *number;
    @property (nonatomic, assign) int user_id;
    
    @end
    
    Model.m
    #import "Model.h"
    
    @implementation Model
    
      - (void)encodeWithCoder:(nonnull NSCoder *)aCoder {
    [aCoder encodeObject:_name forKey:@"name"];
    [aCoder encodeObject:_number forKey:@"number"];
    [aCoder encodeObject:[NSNumber numberWithInt:_user_id] forKey:@"user_id"];
    }
    
    - (nullable instancetype)initWithCoder:(nonnull NSCoder *)aDecoder {
    self = [super init];
    if (self) {
        _name = [aDecoder decodeObjectForKey:@"name"];
        _number = [aDecoder decodeObjectForKey:@"number"];
        _user_id = [[aDecoder   decodeObjectForKey:@"user_id"] intValue];
        }
        return self;
    }
    @end
    
  2. 在需要打包成NSData的地方
    //存数据
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:model];
    [[NSUserDefaults standardUserDefaults] setObject:data forKey:@"data"];
    
    //取数据
    NSData *daa = [[NSUserDefaults standardUserDefaults] objectForKey:@"data"];
    Model *newModel = [NSKeyedUnarchiver unarchiveObjectWithData:daa];
    

你可能感兴趣的:(NSUserDefault用法)