NSUserDefaults保存对象数组报错

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

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

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

模型数据的代码

#import 

@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];

 

转载于:https://www.cnblogs.com/liyy2015/p/9651282.html

你可能感兴趣的:(NSUserDefaults保存对象数组报错)