控制台打印信息如下:
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"];