Broderick
Broderick

Reputation: 77

NSUserDefaults - Inserting array as object not working

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.

Upvotes: 1

Views: 52

Answers (1)

Catfish_Man
Catfish_Man

Reputation: 41831

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.

Upvotes: 3

Related Questions