让我先说一下我的代码被故意隐藏了一点。我知道名字不会好。我正在尝试使用新的 iOS 8 功能向我的应用程序添加一个小部件。我将此链接用作教程
现在,到目前为止,当我的应用程序中调用我的提交按钮时,我的 ViewController 中有这个。到这个时候,我已经在该数组中传递了所有数据。
//Passes the array of times to the shared group to be called by the notification center widget.
NSUserDefaults *sharedDefaults = [[NSUserDefaults alloc] initWithSuiteName:@"group.myGroup.TodayExtensionSharingDefaults"];
NSData *encodedArray = [NSKeyedArchiver archivedDataWithRootObject:tableViewController.TimeArray];
[sharedDefaults setObject:encodedArray forKey:@"TimesArray"];
[sharedDefaults synchronize];
但是,我的数组存储了我创建的自定义数据模型,所以在我的数据模型中我有:
- (void)encodeWithCoder:(NSCoder *)encoder {
//Encode properties, other class variables, etc
[encoder encodeInt:_stopNumber forKey:@"stopNumber"];
[encoder encodeObject:_route forKey:@"route"];
[encoder encodeObject:_number forKey:@"number"];
[encoder encodeInt:_time forKey:@"time"];
[encoder encodeObject:_minutesOrApproaching forKey:@"@minutesOrApproaching"];
[encoder encodeObject:_noPrediction forKey:@"noPrediction"];
}
- (id)initWithCoder:(NSCoder *)decoder {
self = [super init];
if(self) {
//decode properties, other class vars
_stopNumber = [decoder decodeIntForKey:@"stopNumber"];
_route = [decoder decodeObjectForKey:@"route"];
_number = [decoder decodeObjectForKey:@"number"];
_time = [decoder decodeIntForKey:@"time"];
_minutesOrApproaching = [decoder decodeObjectForKey:@"minutesOrApproaching"];
_noPrediction = [decoder decodeObjectForKey:@"noPrediction"];
}
return self;
}
然后在我的小部件中,我调用了以下代码:
NSUserDefaults *defaults = [[NSUserDefaults alloc] initWithSuiteName:@"group.myGroup.TodayExtensionSharingDefaults"];
NSData *myDecodedObject = [defaults objectForKey: @"TimesArray"];
NSArray *decodedArray =[NSKeyedUnarchiver unarchiveObjectWithData: myDecodedObject];
int i = 0;
for (ETA *eta in decodedArray) {
if(i == 0){
_stopNumber.text = eta.number;
}
UILabel *label = [timeSlots objectAtIndex:i];
label.text = eta.minutesOrApproaching;
i++;
}
我的问题是我不断得到:
* 由于未捕获的异常“NSInvalidUnarchiveOperationException”而终止应用程序,原因:“* -[NSKeyedUnarchiver decodeObjectForKey:]:无法解码类对象 (ETA)”在此处输入代码
所以我有点不高兴,因为我不知道我在这里做错了什么。如果有人能帮助我指出正确的方向,那就太好了。再次感谢!