1

Here is my code:

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];

The error being thrown is: -[__NSArrayI insertObject:atIndex:]: unrecognized selector sent to instance 0x170200150

It seems like the problem is when I insert a dictionary into the array, but the code for doing that is correct so I wonder if there is a problem in how I retrieve the array from NSUserDefaults..

Also, when I test the app, it should return "nil" because I have yet to actually create the NSUserDefault object and key..

Thank you.

Broderick
  • 77
  • 6

1 Answers1

3

NSUserDefaults always returns immutable objects, even if you set a mutable one. You must make a mutable copy if you want to change something returned from defaults.

Catfish_Man
  • 41,261
  • 11
  • 67
  • 84
  • even after editing the if statement like so it still doesn't work: NSArray *unmutableArray = [NSKeyedUnarchiver unarchiveObjectWithData:arrayData]; NSMutableArray *savedArray = [unmutableArray copy]; [savedArray insertObject:newThoughtDict atIndex:0]; error is in the same place – Broderick Aug 29 '14 at 00:06
  • 2
    copy *also* does not make a mutable copy. You have to call mutableCopy – Catfish_Man Aug 29 '14 at 00:10