luvieere
luvieere

Reputation: 37494

When and why does NSUserDefaults' synchronize method fail?

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?

Upvotes: 5

Views: 3795

Answers (3)

Bruce Tsai
Bruce Tsai

Reputation: 1450

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.

Upvotes: 0

luvieere
luvieere

Reputation: 37494

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.

Upvotes: 0

Nikolai Ruhe
Nikolai Ruhe

Reputation: 81868

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.

Upvotes: 5

Related Questions