views:

365

answers:

2

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?

+1  A: 

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.

Nikolai Ruhe
+1 for the CFPreferencesSynchronize reference, yet it is of certain importance to me to inspect the result of the synchronize call. My app does synchronize its user domain preferences, but I've just realized that that too can fail, and the return value is correct to be NO in that case. 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. Thank you anyway!
luvieere
A: 

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.

luvieere