developerXXX
developerXXX

Reputation: 689

issue with NSUserDefaults (becomes null)

We are developing an iPhone application. The app is available in the app store. We are using NSUserDefaults to store our usertoken value. But some users reports that the usertoken is became null when the app idle (in background) for long time. But normally the value is getting.

The following is the code for storing usertoken in the NSUserDefaults. We are setting the value to the userToken from the login page and signup pages.

[[NSUserDefaults standardUserDefaults] setObject:userToken forKey:USER_TOEKN];

I have not called synchronize after setting value to NSUserDefaults. Could you please help

Upvotes: 1

Views: 338

Answers (2)

Irshad Mansuri
Irshad Mansuri

Reputation: 407

Try something like this:

 NSUserDefaults  *udf = [NSUserDefaults standardUserDefaults];
 [udf setObject:userToken forKey:USER_TOEKN];
 [udf synchronize];

It will store your value permanently.

Upvotes: 0

thegrinner
thegrinner

Reputation: 12243

You need to call [[NSUserDefaults standardUserDefaults] synchronize]; if your app is going to be backgrounded - my guess is the app idles before the defaults automatically synchronizes. From the documentation:

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.

As for where to do this, take a look at applicationWillResignActive: and applicationDidEnterBackground: in your Application Delegate.

Upvotes: 2

Related Questions