1
这里对象是我的代码:NSUserDefaults的 - 插入阵列不工作
NSMutableDictionary *newThoughtDict = [[NSMutableDictionary alloc] init];
[newThoughtDict setObject:self.triggerOne.text forKey:@"thought"];
[newThoughtDict setObject:self.date forKey:@"date"];
NSDate *currentDate = [[NSDate alloc] initWithTimeIntervalSince1970:NSTimeIntervalSince1970];
[newThoughtDict setObject:currentDate forKey:@"date"];
NSUserDefaults *currentDefaults = [NSUserDefaults standardUserDefaults];
NSData *arrayData = [currentDefaults objectForKey:@"thoughtArray"];
if (arrayData != nil)
{
NSMutableArray *savedArray = [NSKeyedUnarchiver unarchiveObjectWithData:arrayData];
[savedArray insertObject:newThoughtDict atIndex:0]; //<---error being thrown here
[currentDefaults setObject:[NSKeyedArchiver archivedDataWithRootObject:savedArray] forKey:@"thoughtArray"];
[currentDefaults synchronize];
被抛出的错误是: - [__ NSArrayI insertObject:atIndex:]:无法识别的选择发送到实例0x170200150
似乎像问题是当我插入一个字典到数组,但代码做这是正确的,所以我想知道如何从NSUserDefaults检索数组是否有问题..
此外,当我测试应用程序,它应该返回“零”,因为我还没有真正c reate NSUserDefault对象和密钥..
谢谢。
即使在编辑if语句之后,它仍然不起作用:NSArray * unmutableArray = [NSKeyedUnarchiver unarchiveObjectWithData:arrayData]; NSMutableArray * savedArray = [unmutableArray copy]; [savedArray insertObject:newThoughtDict atIndex:0]; 错误是在同一个地方 – Broderick 2014-08-29 00:06:11
副本*也*不会做一个可变的副本。你必须调用mutableCopy – 2014-08-29 00:10:06