Reputation: 315
I'm new and stuck any help would be great! I am using Xcode to build my app.
I have an IBAction "button pressed", this generates random numbers, then I have a bunch of if statements. Ultimately if things match up my long long variable "coins" has a numeric value. Right now I just change that value as in coins = coins + 10 and then display it in a UILabel. I now need to store that value, after all the calculations, whenever the user presses the button. So that their total of "coins" is being added to or subtracted from. Additionally I will want to add and In App Purchase that ads to the "coins" variable. So I know I need a way to store the value, even when the app is closed and re-opened.
Is there a way to use NSUserDefaults to store that value, either within the original IBAction buttonPressed? Also Or any help at all or suggestions would be great! Thanks and sorry if this sounds lame, but I'm on my first app :)
Upvotes: 0
Views: 693
Reputation: 11841
To store a number in NSUserDefaults:
[[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithUnsignedLongLong:coins] forKey:@"coins"];
To retrieve from NSUserDefaults and store it into coins:
coins = [[[NSUserDefaults standardUserDefaults] objectForKey:@"coins"] unsignedLongLongValue];
This is assuming you've declared coins as being an unsigned long long, and not a signed one. Also, there are convenience methods for storing NSIntegers if you want to go through those.
EDIT: Just realized you want to have IAPs, should've read more carefully. I recommend against storing anything of value (passwords, usernames, purchasable currency, highscores that can be submitted to an online leaderboard, etc) in NSUserDefaults. It's stored as a simple .plist
(XML) which could be edited relatively easily as far as I understand.
Upvotes: 1