NSUserDefaults数据保存报错:Attempt to
2018-07-14 本文已影响1人
honey缘木鱼
在使用NSUserDefaults的时候插入数据有时候会报以下错误:
1.这种错误的原因是插入了不识别的PaymentModel数据类型,NSUserDefaults支持的数据类型有NSString、 NSNumber、NSDate、 NSArray、NSDictionary、BOOL、NSInteger、NSFloat等系统定义的数据类型。想保存自定义的数据类型时,我们可以转成NSData再存入。
将PaymentModel类型变成NSData类型就必须实现归档,在PaymentModel.h文件中遵守NSCoding协议,在PaymentModel.m文件中实现encodeWithCoder和initWithCoder 方法。如下所示:
PaymentModel.h
@interface PaymentModel : NSObject<NSCoding>
//标题
@property (nonatomic, copy)NSString *title;
//图片
@property (nonatomic, copy)NSString *picture;
@end
PaymentModel.m
#import "PaymentModel.h"
@implementation PaymentModel
- (void)encodeWithCoder:(NSCoder *)aCoder {
[aCoder encodeObject:self.title forKey:@"title"];
[aCoder encodeObject:self.picture forKey:@"picture"];
}
- (id)initWithCoder:(NSCoder *)aDecoder {
if (self = [super init]) {
self.title = [aDecoder decodeObjectForKey:@"title"];
self.picture = [aDecoder decodeObjectForKey:@"picture"];
}
return self;
}
@end
2.有时NSUserDefaults报存数组,字典,还是报错,原因是我里边的数据结构有"<null>",而NSUserDefaults是不能被成功解析并存入的,所有在存入之前需要将里边的"<null>"改成""即可。