iPhone: preserve NSUserDefaults values when application is killed

前提是你 提交于 2019-12-02 04:40:40

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];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!