NSUserdefault 存储自定义对象

控制台打印信息如下:

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值