IOS: store an array with NSUserDefault

前端 未结 6 916
南旧
南旧 2021-02-06 05:58

I want to store an array with NSUserDefault, then, I put in applicationDidEnterBackground

[[NSUserDefaults standardUserDefaults] setObj         


        
相关标签:
6条回答
  • 2021-02-06 06:31

    Save NSUserDefaults at

    - (void)applicationWillTerminate:(UIApplication *)application 
    
    0 讨论(0)
  • 2021-02-06 06:32

    Do not forget to sync the buffer before going into background:

    [[NSUserDefaults standardUserDefaults] synchronize];
    
    0 讨论(0)
  • 2021-02-06 06:43

    and don't forget to use the encodeWithCoder and initWithCoder inside the object that you are trying to save and that is contained in the array

    0 讨论(0)
  • 2021-02-06 06:45

    set

    [[NSUserDefaults standardUserDefaults] setObject:myArray forKey:@"myArray"];
    

    in

    applicationWillTerminate
    
    0 讨论(0)
  • 2021-02-06 06:49

    Store the object in NSUserDefaults in -applicationWillTerminate:, if it hasn't already been saved by the invocation of -applicationDidEnterBackground: (i.e. check if multitasking is supported, if it is, then don't save it because it's already been saved.)

    - (void) applicationWillTerminate:(UIApplication *) app {
        if([[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)] &&
           ![[UIDevice currentDevice] isMultitaskingSupported]) {
           [[NSUserDefaults standardUserDefaults] setObject:myArray forKey:@"myArray"];
        }
    }
    
    0 讨论(0)
  • 2021-02-06 06:55

    The previous answers are all correct, but note that neither applicationDidEnterBackground nor applicationWillTerminate are guaranteed to be called in all situations. You are usually better off storing important data whenever it has changed.

    0 讨论(0)
提交回复
热议问题