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?
3 Answers
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 my cases, I wrongly use NSUserDefaults, and it will fail. For example, I define my own object, and put it into NSUserDefaults or NSDictionary, it can be put, but it will fail when synchronize. Because NSUserDefaults doesn't support every kind of object. As I know, NSString, NSNumber, NSDictionary....you can google it how to make custom class can be stored in NSUserDefaults.