保存自定义对象的NSMutableArray

时间:2014-03-07 17:05:41

标签: ios objective-c nsmutablearray save nsuserdefaults

我正在尝试将NSMutableArray保存到NSUserDeafults。我已经实现了NSCoding协议方法

-(id)initWithCoder:(NSCoder*)aDecoder{
self = [super init];
if(self!= nil){
    self.subject = [aDecoder decodeObjectForKey:@"subj"];
    self.notes = [aDecoder decodeObjectForKey:@"notes"];
    self.dateDue = [aDecoder decodeObjectForKey:@"date"];
    self.done = [[aDecoder  decodeObjectForKey:@"done"] boolValue];
    self.importancy = [aDecoder decodeObjectForKey:@"imp"];
}
return self;
}

-(void)encodeWithCoder:(NSCoder*)enCoder{
[enCoder encodeObject:self.subject forKey:@"subj"];
[enCoder encodeObject:self.notes forKey:@"notes"];
[enCoder encodeObject:self.dateDue forKey:@"date"];
[enCoder encodeObject:self.importancy forKey:@"imp"];
[enCoder encodeObject:[NSNumber numberWithBool:self.done] forKey:@"done"];
}

我像这样保存

    [[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:hwArray] forKey:ARRAY_KEY];

并且像这样得到它

NSUserDefaults *currentDefaults = [NSUserDefaults standardUserDefaults];
    NSData *hwData = [currentDefaults objectForKey:ARRAY_KEY];
    if (hwData != nil)
    {
        NSLog(@"data is not nil");
        NSArray *savedHWArray = [NSKeyedUnarchiver unarchiveObjectWithData:hwData];
        if (savedHWArray != nil){
            NSLog(@"initiating array");
            hwArray = [[NSMutableArray alloc] initWithArray:savedHWArray];
            NSLog(@"hw array count: %i",[hwArray count]);
        }
        else{
            hwArray = [[NSMutableArray alloc] init];
        }
    }

根据this question看起来很完美,但即使我已经将对象放入数组并加载它,数组在另一次运行中总是为零,我似乎无法加载它。关于问题是什么的任何想法?

1 个答案:

答案 0 :(得分:0)

另一种选择是将对象写入文件而不是NSUserDefaults。查看此question here的答案,获取有关如何执行此操作的完整代码示例。