Is it mandatory to call NSUserDefaults synchronize method?

前端 未结 4 618
天命终不由人
天命终不由人 2020-12-16 14:36

Please, anyone, help me: Is calling NSUserDefaults\'s synchronize() method mandatory?. If I don\'t call it, what will happen? My application is wor

4条回答
  •  时光取名叫无心
    2020-12-16 14:50

    As others have said, you don't normally have to call synchronize at all.

    Normally the system calls it for you so your defaults changes get written.

    However, when working with Xcode it's pretty common to terminate your app by pressing command period or clicking the stop button. In that case it terminates the app without warning and your user defaults changes will quite likely not be written out, and will be lost.

    This can be a good thing or a bad thing, depending on what you want. It's certainly confusing.

    You can "fix" it by calling synchronize each time you make a change, or on some time interval. However that does slow your app down and increase it's power requirements (both by very small amounts.) If you are in a loop, writing changes to 10,000 server or Core Data records, and you change user defaults after each pass, then calling synchronize after each one might have a measurable effect on app speed and on battery life. In most cases you're not likely to notice the difference however.

提交回复
热议问题