我有我保存到NSUserDefaults的,含有我的自定义类赋值,符合NSCoding协议的阵列的阵列。阵列保存和装载适当,我可以验证该阵列的检索到的第一对象是类的分配。当我尝试访问的分配对象的实例变量数组中的问题发生。它崩溃,我得到以下错误:

*** -[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;
}
有帮助吗?

解决方案

回答我自己的问题。在的initWithCoder,我需要保留所有我被解码的对象:

//Example    
title = [[coder decodeObjectForKey:@"title"] retain];

现在一切精美的作品。 :)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top