我正在尝试从NSUserdefaults解码我的对象。 如果我调试函数initWithCoder,它执行正常,但是当我查看我解码的对象时,所有属性都是零。
我的initWithCoder功能:
-(id)initWithCoder:(NSCoder *)decoder
{
self = [super init];
if ( self != nil )
{
//decode the properties
self.SGTIN = [decoder decodeObjectForKey:@"SGTIN"];
self.GTIN = [decoder decodeObjectForKey:@"GTIN"];
self.SerialNumber = [decoder decodeObjectForKey:@"SerialNumber"];
self.Product = [decoder decodeObjectForKey:@"Product"];
self.DateTimeScanned = [decoder decodeObjectForKey:@"DateTimeScanned"];
self.Loaded = [decoder decodeBoolForKey:@"Loaded"];
}
return self;
}
解码对象的代码: NSDictionary * tempDictionary = [[NSUserDefaults standardUserDefaults] dictionaryRepresentation];
NSArray *tempArray =[tempDictionary allKeys];
for (NSString *key in tempArray){
if ([key length] > 8) {
if ([[key substringToIndex:8] isEqualToString:@"INXITEM:"]) {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData *encodedObject = [defaults objectForKey:key];
ScannedItem *SITemp = (ScannedItem *)[NSKeyedUnarchiver unarchiveObjectWithData:encodedObject];
}
}
}
刚刚找到它......
这是因为属性Loaded(bool)是一个新属性,并且NSUserDefaults中保存的对象不包含该属性。
清理了我的NSUserDefaults,现在一切都还好......
答案 0 :(得分:0)
您没有调用正确的超类方法。
应该是
self = [super initWithCoder:decoder];
答案 1 :(得分:0)
尝试在- (void)encodeWithCoder:(NSCoder *)coder
对象类
ScannedItem
方法
- (void)encodeWithCoder:(NSCoder *)coder {
[coder encodeObject:self.SGTIN forKey:@"SGTIN"];
//encode all properties
}