views:

42

answers:

2

in my previous question i was given some code in order to make up this statment.

favoriteArray is an Mutable Array...

if (![self.favoritesArray containsObject:@"added"])
    {
        [self.favoritesArray addObject:@"added"];
    }

else
{
    [self.favoritesArray removeObject:@"added"];
}
//NSUInteger newRow = [self.favoritesArray count];

NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setObject:self.favoritesArray forKey:@"MyFavorites"]; 

however i can't get @"added" to be removed... when the app loads it automatically loads added in the favorites the added text even after cleaning the code. when i press the button it doesnt remove it. so im guessing there is something wrong

and here is where i load it...

   NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
   NSMutableArray *didContain = [[NSMutableArray alloc] init];
   didContain = [[userDefaults objectForKey:@"MyFavorites"] mutableCopy];

   if ([didContain count] == 0) {
       NSLog (@"zero");

            //
            // no favorites have ever been saved
            //


    } else {

        // load the favorites into some array you synthesized just like before
        self.tableFavoritesData = [[NSMutableArray alloc] init];
        self.tableFavoritesData = [[userDefaults objectForKey:@"MyFavorites"] mutableCopy];
    }
A: 

Just try to add @"added" after the array creation and look if it gets removed printing the array out. Maybe you are not serializing it correctly or adding the value in the right way.

rano
+2  A: 

Your code doesn't make much sense.

To load the array from the defaults:

NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
self.tableFavoritesData = [[userDefaults arrayForKey:@"MyFavorites"] mutableCopy];

Is all there is to do. If you don't have an empty array set up as a default value, you might check for nil:

if (!self.tableFavouritesData)
    self.tableFavoritesData = [[NSMutableArray alloc] init];

Or you won't be able to put anything in it as it will still be nil. (Alternatively use registerDefaults: to register a default value. This is the preferred way and you must do that before actually reading from the defaults, i.e. directly at startup).

Eiko
Assuming that self.tableFavoritesData is a retaining property, you probably want to use `self.tableFavoritesData = [NSMutableArray array];` - otherwise you will leak memory.
St3fan