zoukankan      html  css  js  c++  java
  • NSUserDefaults保存对象数组报错

    在使用NSUserDefaults的时候插入数据有时候会报以下错误:Attempt to set a non-property-list objec

    这种错误的原因是插入了不识别的数据类型,NSUserDefaults支持的数据类型有NSString、 NSNumber、NSDate、 NSArray、NSDictionary、BOOL、NSInteger、NSFloat等系统定义的数据类型。

    解决办法把数组归档之后再进行存储直接上代码

    模型数据的代码

    #import <Foundation/Foundation.h>
    
    @interface itemModel : NSObject
    @property(nonatomic,copy)NSString* name;
    @property(nonatomic,copy)NSString* number;
    
    - (instancetype)initWithDict:(NSDictionary *)dict;
    + (instancetype)appInfoWithDict:(NSDictionary *)dict;
    + (NSArray *)appinfoArrayWithArray:(NSArray *)array;
    
    @end
    #import "itemModel.h"
    @interface itemModel ()
    
    
    @end
    @implementation itemModel
    
    - (instancetype)initWithDict:(NSDictionary *)dict
    {
        self = [super init];
        if (self) {
            [self setValuesForKeysWithDictionary:dict];
        }
        return self;
    }
    
    + (instancetype)appInfoWithDict:(NSDictionary *)dict
    {
        return [[self alloc] initWithDict:dict];
    }
    -(void)setValue:(id)value forUndefinedKey:(NSString *)key{
        
    }
    + (NSArray *)appinfoArrayWithArray:(NSArray *)arr
    {
        NSMutableArray *arrayM = [NSMutableArray array];
        
        for (NSDictionary *dict in arr) {
            [arrayM addObject:[self appInfoWithDict:dict]];
        }
        return arrayM;
    }
    
    -(void)encodeWithCoder:(NSCoder *)aCoder
    {
        [aCoder encodeObject:_name forKey:@"name"];
     
        [aCoder encodeObject:_number forKey:@"number"];
    }
    
    - (id)initWithCoder:(NSCoder*)aDecoder
    
    {
        
        if (self = [super init]) {
           
            _name = [aDecoder decodeObjectForKey:@"name"];
            _number = [aDecoder decodeObjectForKey:@"number"];
        }
        
        return self;
        
    }
    @end
    使用方法
    //解档获得数组
    NSData * data= [[NSUserDefaults standardUserDefaults]objectForKey:@"key"]; NSArray * appArray = [NSKeyedUnarchiver unarchiveObjectWithData:data]; NSMutableArray * mut = [NSMutableArray arrayWithArray:appArray]; [mut addObject:mode]; //归档存储数组 NSData *data1 = [NSKeyedArchiver archivedDataWithRootObject:[mut mutableCopy]]; [userDefaults setObject:data1 forKey:@"key"]; [userDefaults synchronize];
  • 相关阅读:
    核心数据类型
    Python入门
    [多校联考2019(Round 4 T2)][51nod 1288]汽油补给(ST表+单调栈)
    [Codeforces 1228E]Another Filling the Grid (排列组合+容斥原理)
    [luogu5339] [TJOI2019]唱、跳、rap和篮球(容斥原理+组合数学)(不用NTT)
    用生成函数推导数列的通项公式
    [Luogu 5465] [LOJ 6435] [PKUSC2018]星际穿越(倍增)
    [BZOJ4569] [Luogu 3295] [SCOI2016]萌萌哒(并查集+倍增)
    [BZOJ4444] [Luogu 4155] [LOJ 2007] [SCOI2015]国旗计划(倍增)
    倍增好题记录
  • 原文地址:https://www.cnblogs.com/liyy2015/p/9651282.html
Copyright © 2011-2022 走看看