我有一个数组,我保存到NSUserDefaults,包含我的自定义类Assignment的数组,它符合NSCoding协议。数组正确保存和加载,我可以验证检索到的数组的第一个对象是否为类Assignment。当我尝试访问数组中的Assignment对象的ivars时,会发生此问题。它崩溃了,我得到以下错误:
*** -[CFString respondsToSelector:]: message sent to deallocated instance 0x3948d60
以下是我用来保存到用户默认值的代码。请注意,我还检索并检查保存的对象以进行调试。
-(void)saveToUserDefaults:(NSArray*)myArray
{
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
if (standardUserDefaults) {
[standardUserDefaults setObject:[NSKeyedArchiver archivedDataWithRootObject:myArray] forKey:@"Assignments"];
[standardUserDefaults synchronize];
}
NSLog(@"Assignments array saved. (%d assignments in array)",[myArray count]);
NSData *dataCheck = [[NSData alloc] initWithData:[standardUserDefaults objectForKey:@"Assignments"]];
NSArray *arrayCheck = [[NSArray alloc] initWithArray:[NSKeyedUnarchiver unarchiveObjectWithData:dataCheck]];
NSLog(@"Checking saved array (%d assignments in array)",[arrayCheck count]);
if ([[arrayCheck objectAtIndex:0] isKindOfClass:[Assignment class]]) {
NSLog(@"It's of the class Assignment.");
}
Assignment *testAssignment = [[Assignment alloc] initWithAssignment:[arrayCheck objectAtIndex:0]];
NSLog(@"Title: %@ Course: %@",[testAssignment title],[testAssignment course]);
}
在我分配testAssignment之前一切都很好,这是发生崩溃的地方。有没有人有任何想法?
编辑:这是我在Assignment类中的NSCoding方法:
- (void)encodeWithCoder:(NSCoder *)coder {
[coder encodeObject:title forKey:@"title"];
[coder encodeObject:course forKey:@"course"];
[coder encodeObject:dueDate forKey:@"dueDate"];
[coder encodeObject:notes forKey:@"notes"];
}
- (id)initWithCoder:(NSCoder *)coder {
self = [[Assignment alloc] init];
if (self != nil)
{
title = [coder decodeObjectForKey:@"title"];
course = [coder decodeObjectForKey:@"course"];
dueDate = [coder decodeObjectForKey:@"dueDate"];
notes = [coder decodeObjectForKey:@"notes"];
}
return self;
}
答案 0 :(得分:3)
回答了我自己的问题。在initWithCoder中,我需要保留我正在解码的所有对象:
//Example
title = [[coder decodeObjectForKey:@"title"] retain];
现在一切都很美好。 :)