Nimrod Shai
Nimrod Shai

Reputation: 1179

MutableDictionary turns immutable

In my first function i create an NSMutableDictionary and saves it in an array.

NSMutableArray* tempPlayersArray = [NSMutableArray arrayWithArray: [[NSUserDefaults standardUserDefaults] arrayForKey: @"kgpsTempArray"]];
NSMutableDictionary *tempPlayerDictArray = [[NSMutableDictionary alloc] init];

if (!(userDeviceName)) {
    [tempPlayerDictArray setValue:userDeviceName forKey:@"DeviceName"];
}else{
    [tempPlayerDictArray setValue:@"empty" forKey:@"DeviceName"];
}
[tempPlayersArray addObject:tempPlayerDictArray];

[defaults setObject:tempPlayersArray forKey:@"kgpsTempArray"];
[defaults synchronize];

In my second function i get it as NSCFDictionary - which is not mutable.

NSMutableArray* tempPlayersArray = [NSMutableArray arrayWithArray: [[NSUserDefaults standardUserDefaults] arrayForKey: @"kgpsTempArray"]];
NSMutableDictionary *dictionaryForSearching = [[NSMutableDictionary alloc] init];
NSLog(@"%@",[dictionaryForSearching class]);

dictionaryForSearching = [tempPlayersArray objectAtIndex:index];

NSLog(@"%@",[[tempPlayersArray objectAtIndex:index] class]);
NSLog(@"%@",[dictionaryForSearching class]);

The first log shows "NSDictionaryM".
The second log shows "NSCFDictionary".
And the third shows "NSCFDictionary" as well...

Can anyone explain me why? And how to fix it?

Upvotes: 0

Views: 143

Answers (3)

Anoop Vaidya
Anoop Vaidya

Reputation: 46543

Every thing depends from here:

NSMutableArray* tempPlayersArray = [NSMutableArray arrayWithArray: [[NSUserDefaults standardUserDefaults] arrayForKey: @"kgpsTempArray"]];

Reading NSUserDefaults always give you Immutable object.

Upvotes: 0

justin
justin

Reputation: 104698

Yes, NSUserDefaults is free to copy, persist, and deserialize as it likes. Assume it does not return mutable objects. If you need a mutable object, make a mutable copy.

Upvotes: 0

Antonio MG
Antonio MG

Reputation: 20410

NSUserDefaults works with inmutable objects, so that's the reason that when you return your dictionary it's changed.

You can try this:

dictionaryForSearching = [[NSMutableDictionary alloc] initWithDictionary:[tempPlayersArray objectAtIndex:index]];

Upvotes: 4

Related Questions