NSuserdefault issue after restart my iphone

hi,guys.There's a issue about my app about NSuserdefault. Everything is arlright if i stay in the app, once i close my app, and restart it.Datas from nsuserdefault is gone(nil). i tried to add and delete synchronize method , but its not working. But this situation only happens in ios 18.(at least ios12 and ios16 is alright).

Answered by mutou519 in 845765022

strange thing is, the same code to save value by using userdefault.Another project is all good,and its not disappear after swiping up the app.But in this project, it can not save and remove correctly.

What code are you using to write to and read from the defaults?

If you run the app in the Simulator you should be able to see the plist file for your app in the filesystem. You can check whether data has been written to it correctly, and that it's being read back correctly.

@mutou519 have you checked that you saved to userDefaults ?

May be, when you quit the app (by swiping up ?), you don't go through the code that saves userDefaults.

To check: in the part of code where you intent to save, add a print statement to check in logs that it was effectively done.

If that's the case, you should save userDefaults in SceneDelegate:

    func sceneDidEnterBackground(_ scene: UIScene) {
     // Save userDefaults
    }

and also possibly here:

    func sceneDidDisconnect(_ scene: UIScene) {
        
    }

and read here:

    func sceneWillEnterForeground(_ scene: UIScene) {
        // read userDefaults
    }

You could also save in AppDelegate:

    func applicationWillTerminate(_ application: UIApplication) {
        // Save userDefaults
    }
Accepted Answer

strange thing is, the same code to save value by using userdefault.Another project is all good,and its not disappear after swiping up the app.But in this project, it can not save and remove correctly.

NSuserdefault issue after restart my iphone
 
 
Q