1

I am trying to implement "Add to Favorites" functionality using NSUserDefaults. So far I have written following code.

- (void)favouriteButtonClicked:(id)sender
{
favselected = !favselected; // favselected is BOOL property
MyAppDelegate *appDelegate = (MyAppDelegate *)[[UIApplication sharedApplication] delegate];
NSString* viewname = @"custom";

if(favselected) {
    [favButton setBackgroundImage:[UIImage imageNamed:@"selected.png"] forState:UIControlStateNormal];
    [appDelegate addTOFavourites:self.ViewID viewType:self.ViewType];
} else {
    [favButton setBackgroundImage:[UIImage imageNamed:@"unselected.png"] forState:UIControlStateNormal];
    [appDelegate removeFromFavourites:self.ViewID viewType:self.ViewType];
}
}

It is working fine as long as my application is running but when I killed my application, I am losing all my stored values so when next time view loaded, in viewload isAddedToFavorites method returns false. Is there anyway to preserve my values? Am I missing something?

    if([appDelegate isAddedToFavorites:self.ViewID]) {
        [favButton setBackgroundImage:[UIImage imageNamed:@"selected.png"] forState:UIControlStateNormal];
        favselected = YES;
    } else {
        [favButton setBackgroundImage:[UIImage imageNamed:@"unselected.png"] forState:UIControlStateNormal];
        favselected = NO;
    }

Edit:

I tried using NSMutableDictionary as I have to add multiple key-values but following method always display Count=0 even after adding object to dictionary. Any help would be really appreciated. Thank you.

-(BOOL)isAddedToFavorites:(NSString*)viewID {
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
NSMutableDictionary *favourites = [[standardUserDefaults objectForKey:kFavouriteItemsKey] mutableCopy];

if(favourites && [[favourites objectForKey:kFavouriteItemsKey] objectForKey:viewID])
    return YES;

return NO;
}

-(void)addToFavourites:(NSString*)viewID viewType:(NSString*)viewType {

NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
NSMutableDictionary *dict = [[standardUserDefaults objectForKey:kFavouriteItemsKey] mutableCopy];

if(standardUserDefaults) {
    if(![dict objectForKey:viewID])
        [dict setObject:viewType forKey:viewID]; // It is coming here but still count zero!

    NSLog(@"count = %d", [dict count]);

    [standardUserDefaults setObject:dict  forKey:kFavouriteItemsKey]; // Always dict remains null with 0 objects in it
    [standardUserDefaults synchronize];
    [dict release];
}
}

-(void)removeFromFavourites:(NSString*)viewID viewType:(NSString*)viewType {

NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
NSMutableDictionary *dict = [[standardUserDefaults objectForKey:kFavouriteItemsKey] mutableCopy];

if(standardUserDefaults) {
    if ([dict objectForKey:viewID])
        [dict removeObjectForKey:viewID];

    [standardUserDefaults setObject:dict  forKey:kFavouriteItemsKey];
    [standardUserDefaults synchronize];
    [dict release];
}
}

Thanks.

Paresh Masani
  • 7,474
  • 12
  • 73
  • 139
  • Try logging out *everything* in your posted code. – Moshe Jul 06 '11 at 11:54
  • Also, have you initialized your favorites array somewhere? – Moshe Jul 06 '11 at 11:54
  • What you mean by logging out everything? I tried changing the kFavoriteItemsKey but no luck. I am already initializing dictionary objects already with existed data. If data not available it will set to null but still i will put separate initialization and see it that makes any difference. – Paresh Masani Jul 06 '11 at 12:02
  • Log all values to the console using NSLog statements. – Moshe Jul 06 '11 at 12:12
  • That I already did it! ViewID and ViewType is coming correct as passed. Also [dict setObject...] getting executed but still after that dict is staying with 0 objects!! – Paresh Masani Jul 06 '11 at 12:43

1 Answers1

3

NSUserDefaults is actually used to store values permanently, in fact if you create any Settings for your program they will be saved as NSUserDefaults.

I think the problem is that you are not saving it with the same key you are retrieving. Try saving like this:

  //To save
  NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  [defaults setObject:appDefaults forKey:kFavouriteItemsKey];
  [[NSUserDefaults standardUserDefaults] synchronize];

  //To retrieve
 NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
 NSMutableDictionary *favourites = [[standardUserDefaults objectForKey:kFavouriteItemsKey]   mutableCopy];

For the dictionary try:

 NSDictionary *myDictionary= [[NSUserDefaults standardUserDefaults] objectForKey:kFavouriteItemsKey];

        // Create a mutable dictionary to replace the old immutable dictionary
    NSMutableDictionary *myMutableDictionary= [NSMutableDictionary dictionaryWithCapacity:[myDictionary count]+1];

        // transfer the old dictionary into the new dictionary
    [myMutableDictionaryaddEntriesFromDictionary:myDictionary];

        // Now add the data
    [myMutableDictionary setObject:myObject forKey:myKey];
Oscar Gomez
  • 18,436
  • 13
  • 85
  • 118
  • You are right. It was my bad. I had stored some invalid NSData value previously with the same key and that was creating the problem. I have changed key name and it worked! Thank you! BTW, where did this value gets stored on iPhone? How can I delete them without referring to my application? Also, did you see the other question why my counter is always coming to zero? It is still happening. I am not able to store multiple key-values. Basically I am getting current defaults into mutable dictionary, modify them and set modified dictionary to defaults but doesn't seem to be working! – Paresh Masani Jul 05 '11 at 16:31
  • @AppleDeveloper The value gets stored in your applications "sandbox" so it is always referring to your application specifically, however you can just use [[NSUserDefaults standardUserDefaults] removeObjectForKey:myKey]; to delete any NSUserDefaults you want, I am not sure if I saw that question, can you please put the link?, I can look into it. – Oscar Gomez Jul 05 '11 at 16:44
  • Hi OscarMK, I have edited my question and also put comments which will be useful for you to understand question. I am scratching my head since long now. Not able to understand what's going on!! Any help would be really grateful. Thanks. – Paresh Masani Jul 06 '11 at 11:11
  • @AppleDeveloper NSUserDefaults always returns immutable objects, I know you are sending a mutableCopy msg, but for some reason it is not working like that, you can try what i just edited on my answer. – Oscar Gomez Jul 06 '11 at 14:47
  • you are correct. I have to do like you suggested but still last problem is it is not able to synchronize with NSUserDefaults! I have added last three lines in your answer. Any idea why it is not getting stored? Is it may be because of [this](http://stackoverflow.com/questions/471830/why-nsuserdefaults-failed-to-save-nsmutabledictionary-in-iphone-sdk)? I tried converting dictionary to NSData but it looks very strange to me. Not able to get the key again! – Paresh Masani Jul 06 '11 at 15:04
  • Hi OscarMk, I think this topic is totally different and hence I have created new question [here](http://stackoverflow.com/questions/6598198/iphone-not-able-to-store-nsmutabledictionary-to-nsuserdefaults) Thanks for being there! Accepted your initial answer. Please reply me in new thread. Thanks. – Paresh Masani Jul 06 '11 at 15:22