views:

139

answers:

2

I want to have an If statement that allows me to tell whether I have an NSUserDefaults saved or not.

+4  A: 

The point of NSUserDefaults is that it transparently saves your data for you without your intervention, so you can't ask it whether it has saved the data or not.

However, you can force it to save by calling [[NSUserDefaults sharedUserDefaults] synchronize];, which returns a BOOL indicating whether or not the save was successful. The documentation for this method says:

Because this method is automatically invoked at periodic intervals, use this method only if you cannot wait for the automatic synchronization (for example, if your application is about to exit) or if you want to update the user defaults to what is on disk even though you have not made any changes.

Dave DeLong
A: 

I think the question is asking whether or not a particular object is stored in the user defaults, rather than knowing whether or not data was successfully saved.

The user defaults is simply a dictionary, in terms of it's API, so you can attempt to retrieve an object for a given key. If the object returned is not nil, then something has obviously been stored for that key. Conversely, if the the return is nil, then nothing has been stored and you should probably load a default object or carry out some other kind of contingency.

Jasarien