iOS - setObject vs. Synchronize

2020-04-07 18:55发布

Newbie question. If I set an object into NSUserDefault do I also need to Synchronize to be sure the object goes back into NSUserDefault database permanently? I guess what I am asking is, is "setobject" placing the object right back into the database permanently or into some temporary storage that needs to be synchronized to ensure permanent storage?

For example: //below I place a new copy of a list in NSUserDefaults after adding a row of data

userDefaults.setObject(newMutableList, forKey: "itemList")

//do I also need to synchronize right away to be sure database updates permanently?

userDefaults.synchronize() 

My code works without the synchronize, meaning I don't need it. But I want to make sure that skipping the use of synchronize doesn't cause problems in another scenario in future.

Thanks in advance.

2条回答
我想做一个坏孩纸
2楼-- · 2020-04-07 19:27

You use synchronize, to update the database, immediately. If you don't use Synchronize, IOS will do it for you but only periodically. It is a best practice to use synchronize every time you make any change, so that if your app crashes all the changes user made will not be lost.

查看更多
【Aperson】
3楼-- · 2020-04-07 19:43

On iOS 7 and earlier:

When you call -setObject:forKey:, NSUserDefaults schedules a synchronize operation itself for roughly 10 seconds in the future. When that occurs, everything up to that point is saved to persistent storage. The idea here is that you can freely use the set and get methods without paying the significant performance cost of going out to disk every time.

On iOS 8, NSUserDefaults works differently, and the delay is a few milliseconds, rather than 10 seconds, so -synchronize is almost never useful.

On iOS 12, all remaining uses of -synchronize are unnecessary. Note that there may still be cases apps want to call it because they support iOS 11 and earlier.

查看更多
登录 后发表回答