When and why does NSUserDefaults' synchronize method fail? What is the best way to make sure that my values are actually written and commited to NSUserDefaults, so I wouldn't have any problems restoring state after application restart?
The synchronize
method is a higher level API wrapper around the CFPreferencesSynchronize
function. There's nothing about it in the documentation but I presume that synchronize
just returns the result of CFPreferencesSynchronize
. Since this CoreFoundation function can be used to synchronize host (admin) and network based preferences it can fail in some cases.
In the most common case where an app just synchronizes its user domain preferences (in the Library directory of the current user), the function usually does not fail. I think it's safe to just ignore the return value of synchronize
. But that's just my opinion.
In some cases, my app was trying to write a nil value with a certain key, and that was causing synchronize to fail. Now I'm checking that value for nil before the save and the problem is fixed.