Showing posts with label mutable method sent to immutable object. Show all posts
Showing posts with label mutable method sent to immutable object. Show all posts

Wednesday, February 6, 2013

NSUserDefaults-Mutable method sent to immutable object

As the documentation for NSUserDefaults says: "Values returned from NSUserDefaults are immutable, even if you set a mutable object as the value." Whenever you want to change a collection you get from NSUserDefaults you have to get the imutable version, make a mutableCopy, modify that, and set it back again.

For E.g:


   NSMutableArray *placesT= nil;
   NSrray *tempArray = [[NSUserDefaults standardUserDefaults] objectForKey:@"placesT"];

if (tempArray) {
    placeT = [tempArray mutableCopy];
} else {
    placesT=[[NSMutableArray alloc] init];
}

[placesT addObject: [NSString stringWithFormat:@"%@", tagF.text] ];

NSUserDefaults *tUD=[NSUserDefaults standardUserDefaults];
[tUD setObject:placesT forKey:@"placesT"];
[tUD synchronize];