John55
John55

Reputation: 311

NSUserDefaults Not Saving Data Objective C

I am creating this application which consists of the users score. When they exit out of the app, there score will be saved. I am doing that through NSUserDefaults which works fine. The problem is that the users score can be manipulated in other views. For example, they can use their score to buy stuff, etc. To do this I am saving the score in NSUserDefaults and then just retrieving that saved data in the next view. The problem is that the data is not being saved for some reason. I have a timer that runs every second that saves the score and I save it using an IBAction when I click the button to go to the next view. Here is what I use to initialize the variable:

score = [[[NSUserDefaults standardUserDefaults] objectForKey:@"score"] longLongValue];

And this is to save it:

[[NSUserDefaults standardUserDefaults] setObject:@(score) forKey:@"score"];

I am using a long long variable which is why I have it as an object as opposed to integer. I do not understand why the values are getting changed as I change views. Anytime I manipulate the score value, I save it. At the top of each view I am declaring it. I realize that other people have posted similar questions, and I have viewed them all. Those responses did not solve my problem which is why I asked on here. Synchronize

[[NSUserDefaults standardUserDefaults] synchronize];

has not worked for me either.

Upvotes: 0

Views: 1400

Answers (2)

Dipen Panchasara
Dipen Panchasara

Reputation: 13600

Only thing you are missing is, synchronize you are not telling NSUserDefault to write data on disc.

// *** Get your score value ***
score = [[[NSUserDefaults standardUserDefaults] objectForKey:@"score"] longLongValue];

// *** manipulate it if needed ***
score+=100;

// *** save it back to `NSUserDefaults` ***
[[NSUserDefaults standardUserDefaults] setObject:@(score) forKey:@"score"];

// *** Synchronize your updates to `NSUserDefaults` by calling it, it immediately write data to disc ***
[[NSUserDefaults standardUserDefaults] synchronize];

For more details about NSUserDefaults read Apple Documentation

Upvotes: 2

testing tcyonline
testing tcyonline

Reputation: 47

Use this. This will save the value

[[NSUserDefaults standardUserDefaults] setObject:@(score) forKey:@"score"];

[[NSUserDefaults standardUserDefaults] synchronize];

Upvotes: 1

Related Questions