关闭

NSUserdefault 存储自定义对象

标签: 自定义对象存储NSUserDefaults
6913人阅读 评论(0) 收藏 举报
分类:

控制台打印信息如下:

      2013-12-04 11:11:43.573 MaiMaiCircle[837:a0b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSUserDefaults setObject:forKey:]: attempt to insert non-property list object (
    "<AddressItem: 0x1096d09a0>"
) for key addressArray'
*** First throw call stack:

经过资料查询原因是:我在NSUserDefaults中存储了自定义的模型,所以报错.

NSUserDefaults支持的数据格式有:NSNumber(Integer、Float、Double),NSString,NSDate,NSArray,NSDictionary,BOOL类型

如果你要保存其他类型或者自定义类型需要用到archiver需要写encode和decode两个method.


#import "AddressItem.h"

@implementation AddressItem
@synthesize circle;
@synthesize city;
@synthesize detail;
@synthesize userName;
@synthesize telephone;
@synthesize SetAsDefault;

#pragma mark NSCoding
- (void)encodeWithCoder:(NSCoder *)aCoder {
    [aCoder encodeObject:city forKey:@"city"];
    [aCoder encodeObject:circle forKey:@"circle"];
    [aCoder encodeObject:detail forKey:@"detail"];
    [aCoder encodeObject:userName forKey:@"username"];
    [aCoder encodeObject:telephone forKey:@"telephone"];
    [aCoder encodeFloat:SetAsDefault forKey:@"setasdefault"];
}

- (id)initWithCoder:(NSCoder *)aDecoder {
    if (self = [super init]) {
        self.city = [aDecoder decodeObjectForKey:@"city"];
        self.circle = [aDecoder decodeObjectForKey:@"circle"];
        self.detail = [aDecoder decodeObjectForKey:@"detail"];
        self.userName = [aDecoder decodeObjectForKey:@"username"];
        self.telephone = [aDecoder decodeObjectForKey:@"telephone"];
        self.SetAsDefault = [aDecoder decodeFloatForKey:@"setasdefault"];
    }
    return self;
}

#pragma mark NSCoping
- (id)copyWithZone:(NSZone *)zone {
    AddressItem *copy = [[[self class] allocWithZone:zone] init];
    copy.city = self.city;
    copy.circle = [self.circle copyWithZone:zone];
    copy.detail = [self.detail copyWithZone:zone];
    copy.userName = [self.userName copyWithZone:zone];
    copy.telephone = [self.telephone copyWithZone:zone];
    copy.SetAsDefault = self.SetAsDefault;
    return copy;
}

@end



反序列化:

 NSData * data = [[NSUserDefaults standardUserDefaults] objectForKey:@"addressArray"];
    NSArray * array = [NSKeyedUnarchiver unarchiveObjectWithData:data];
    self.addressArray = [[NSMutableArray alloc]initWithArray:array];


序列化:

NSMutableArray * array = [[NSMutableArray alloc]init];
    [array addObject:item];
    NSData * data = [NSKeyedArchiver archivedDataWithRootObject:array];
    
    [[NSUserDefaults standardUserDefaults] setObject:data forKey:@"addressArray"];


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:155398次
    • 积分:2091
    • 等级:
    • 排名:第18247名
    • 原创:46篇
    • 转载:53篇
    • 译文:0篇
    • 评论:9条
    文章分类
    最新评论