美文网首页
NSUserDefault 存入NSMutableArray数组

NSUserDefault 存入NSMutableArray数组

作者: 幽玄727 | 来源:发表于2020-11-14 23:53 被阅读0次

    1.NSUserDefault 里面存数据

    NSUserDefaults *currentDefaults = [NSUserDefaults standardUserDefaults];
    
    //需要将你需要存储的数据转成data
    
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:yourObject];
    
    [currentDefaults setObject:data forKey:@"yourKeyName"];
    

    2.接下来就是在 NSUserDefault 里面取数据

    NSData *data = [currentDefaults objectForKey:@"yourKeyName"];
    
    yourObjectType * obj = [NSKeyedUnarchiver unarchiveObjectWithData:data];
    

    3.如果数组中的数据是实体类,则需要遵守NSCoding协议

    @interface MyModel:NSObject<NSCoding>
    @property (copy,nonatomic)NSString * name;
    @property (nonatomic)int age;
    @end
    
    @implementation MyModel
    
    -(instancetype)initWithCoder:(NSCoder *)aDecoder{
        if (self = [super init]) {
            self.name = [aDecoder decodeObjectForKey:@"kName"];
            self.age = [aDecoder decodeInt32ForKey:@"kAge"];
        }
        return self;
    }
    
    -(void)encodeWithCoder:(NSCoder *)aCoder{
        [aCoder encodeObject:self.name forKey:@"kName"];
        [aCoder encodeInt32:self.age forKey:@"kAge"];
    }
    

    相关文章

      网友评论

          本文标题:NSUserDefault 存入NSMutableArray数组

          本文链接:https://www.haomeiwen.com/subject/wrvgbktx.html