Count and store a value in xcode - iphone

Hello everyone I would have a value for the need to save every time I press a button (count), virtually every time a user presses a button in my app should be pressed to keep count of the times (1,2,3,4, etc. etc.) the problem is that that data would be permanently saved, that is, even when you exit the app or restart the device should be saved on the iphone to find it and increase it reopened after the application.
Is there an easier way to CoreData or SqlLite to do this?
thanks

Here is a sample code:
To store it:
[[NSUserDefaults standardUserDefaults] setInteger: intCount forKey:#"Count"];
[[NSUserDefaults standardUserDefaults] synchronize];
To read it:
intCount = [[NSUserDefaults standardUserDefaults] integerForKey: #"Count"];

The easiest way would be use NSUserDefaults to do this, no need for a bigger data store if it's only an integer.
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
int buttonCount = 0;
// Do you count somewhere and add to buttonCount
[defaults setObject:[NSNumber numberWithInt:buttonCount] forKey:#"buttonPress"];
and to retrieve to number back just use
int buttonPress = [[[NSUserDefaults standardUserDefaults] objectForKey:#"buttonPress"] intValue];

NSUserDefaults is the solution. Update the stored value in every button click....

Related

Save score value in one view controller and display on another

I'm developing a game that uses a basic points system for shooting enemies, and that score is then converted to a coins value for unlocking extra guns in the game. So when you play, your score goes up and when you die a screen shows you your score, and how many coins you got from that playthrough (score x 10 at the moment).
I'm looking for the best way to get the coins value and display it on another screen, the gun selection screen, the first time you play and from then on the coins you get from one playthrough will add to the total coins you have, the value displayed on the gun selection screen. And if it is easy to do, a way of encrypting the coins value.
This is what I'm currently using, with NSUserDefaults, in the play game view:
NSUserDefaults *coins = [NSUserDefaults standardUserDefaults];
NSNumber *myCoins = [NSNumber numberWithInt:_killCount*9.4];
_myCoinsInt = [myCoins integerValue];
_totalCoinsInt = _myCoinsInt + _totalCoinsInt;
[coins setObject:myCoins forKey:#"coins"];
[coins synchronize];
NSUserDefaults *totalCoins = [NSUserDefaults standardUserDefaults];
NSNumber *theTotalCoins = [NSNumber numberWithInt:_totalCoinsInt];
[totalCoins setObject:theTotalCoins forKey:#"totalCoins"];
[totalCoins synchronize];
NSLog(#"%#", theTotalCoins);
And in the Gun selection screen, under the viewDidLoad method:
NSUserDefaults *totalCoins = [NSUserDefaults standardUserDefaults];
NSInteger _totalCoinsInt = [totalCoins objectForKey:#"totalCoins"];
NSString *intString = [NSString stringWithFormat:#"%d", _totalCoinsInt];
scoreField.text = intString;
I think the simplest way to go would be to store the amount of coins in the [NSUserDefaults standardUserDefaults] either way, you can do it the way the other answers provided but you're going to need to save that data when your app closes.
I would also back this value up with your server (if you have one) to keep track of different users and to save the values. Check out parse.com if you don't have a web service already.
Example
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//grab coins
int totalCoins = [defaults integerForKey:#"totalCoins"];
//add coins
totalCoins += coinsThisLevel;
//save
[defaults setInteger:totalCoins forKey:#"totalCoins"];
[defaults synchronize];
Are you familiar with the MVC (model-view-controller) design pattern? That's what you need here. I'd do something like create a Coins class, create an instance of it in the app delegate and pass that instance around among the various view controllers. You can have methods in your class for adding more coins, saving the coins value, encrypting if necessary. You can use KVO (key-value observing) to watch your coins instance for changes to a #property so interested parties can do things like update their display when the coins amount changes.
Well for the score I would recommend you save it with NSUserDefault and save it as a label. Some Code:
//Saving
[[NSUserDefaults standardUserDefaults] setInteger:HighScore forKey:#"HighScore"];
//Loading
NSInteger highScore = [[NSUserDefaults standardUserDefaults] integerForKey:#"HighScore"];
Check out the documentation: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSUserDefaults_Class/Reference/Reference.html

Saving incremental int variable

I need to save a variable that increments every time a user hits a button within the app. I've been trying to do that with NSUserDefaults with no success. Here's the code I'm using:
[[NSUserDefaults standardUserDefaults] setInteger:i++ forKey:#"AppCount"];
When I output this in the log, however, I keep getting 0.
Any help would be greatly appreciated.
Try adding:
[[NSUserDefaults standardUserDefaults] synchronize];
After each time you change the value of your integer.
Quoting Apple's documentation on synchronize:
Writes any modifications to the persistent domains to disk and updates
all unmodified persistent domains to what is on disk.
http://developer.apple.com/library/ios/DOCUMENTATION/Cocoa/Reference/Foundation/Classes/NSUserDefaults_Class/Reference/Reference.html#//apple_ref/occ/instm/NSUserDefaults/synchronize
So with this modification, your final code should look like this:
[[NSUserDefaults standardUserDefaults] setInteger:i++ forKey:#"AppCount"];
[[NSUserDefaults standardUserDefaults] synchronize];
EDIT: Actually on second thought, give this a try:
I think the problem is using i++ assumes that the application will always be able to keep track of the count, and every time you re-enter the application i gets reset.
The following works, I just tested it.
if (![[NSUserDefaults standardUserDefaults] integerForKey:#"AppCount"]) {
[[NSUserDefaults standardUserDefaults] setInteger:i forKey:#"AppCount"];
}else{
[[NSUserDefaults standardUserDefaults] setInteger:[[NSUserDefaults standardUserDefaults] integerForKey:#"AppCount"] + 1 forKey:#"AppCount"];
}
[[NSUserDefaults standardUserDefaults] synchronize];
You can use Static NSUIInteger appCount=0;
in the function user taps increase it value appCount++;
that keeps the value in function calls within the app. after app closing you write it to file.
- (void)viewDidLoad {
[super viewDidLoad];
countFirst= [[NSUserDefaults standardUserDefaults]integerForKey:#"Counter"];
countFirst++;
}
Write this wherever you want to increment.
[[NSUserDefaults standardUserDefaults] setInteger:countFirst++ forKey:#"Counter"];

Storing preferences in NSUser Defaults to recall later

Been working on some code streamlining and have realised that it would be really helpful if my app had a preferences system.
Now here's how my code works.
A method runs based upon an integer stored in NSUserDefaults
e.g.
if ([[NSUserDefaults standardUserDefaults] integerForKey:#"scifi1"] == 040){
[self spaceDown];
}
else if ([[NSUserDefaults standardUserDefaults] integerForKey:#"scifi1"] == 10040){
[self ctrldown];
[self spaceDown];
}
Now what I want to do is when I exit the view (via a specific button) is to dump the value of #"scifi1" into a new preference, say for example - an integer named #"savedscifi1"
Now I know how to save integers into NSUserDefaults,
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setInteger:VALUEHERE forKey:#"savedscifi1"];
[userDefaults synchronize];
However - I'm not sure how I can substiture in the value of scifi1 instead of (in this case) 'VALUEHERE' - can anyone help with this? I feel it's really simple but I can't help but think I'm being a bit thick...sleep deprived and approaching a deadline! I know I can't just call up #"scifi1"but beyond that....??
NSInteger value = [[NSUserDefaults standardUserDefaults] integerForKey: ...];
[[NSUserDefaults standardUserDefaults] setInteger: value forKey: ...];

Is there any delegate that fires when I run the iphone application for the first time?

I need to track the download of a certain iphone application. I tried a lot and found out that we could track it from the AppStore. But i need to track that from my application itself. So please help me to identify the method that fires when the application starts for the first time. Thanks.
There's no specific method that fires only on the 1st application launch. You can set a flag in user defaults on application start - so if the flag is not present then that will mean that application launched for the 1st time:
- (void)applicationDidFinishLaunching:(UIApplication *)application {
if (![[NSUserDefaults standardDefaults] boolForKey:#"AlreadyLaunched"]){
// First launch logic
[[NSUserDefaults standardDefaults] setBool:YES forKey:#"AlreadyLaunched"];
[[NSUserDefaults standardDefaults] synchronize];
}
...
}
But i need to track that from my application itself.
No.
But if you really want to do this you could use something like this:
BOOL hasUsedSpyWareFunctions = [[NSUserDefaults standardUserDefaults] boolForKey:#"SpyWareKey"];
if (!hasUsedSpyWareFunctions) {
[self spyOnUser];
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:#"SpyWareKey"];
}
if you are a Pro in spying you only set the key to YES if the method returned successfully (ie a network connection could be established)
There’s no such an event, at least not one that I know of. But what you want can be trivially done using NSUserDefaults. Simply check for some boolean flag and if it’s not there, it’s a first run and you can set the flag:
NSString *const AlreadyRunKey = #"already-run";
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
if (![prefs boolForKey:AlreadyRunKey]) {
[prefs setBool:YES forKey:AlreadyRunKey];
[prefs synchronize];
// do whatever else you want
}

Save And Load A Single Value, iPhone

I have a feeling there is a simple way to do this. I have a number between 1 and 100 and it is stored in a variable called firstValue. This variable is then put into a UILabel. When the user exits my app, I want this firstValue to be saved so that when the app is loaded by the user this number can be re-inserted into the UILabel (firstValueLabel.text).
Many thanks,
Stuart
You can use NSUserDefaults for this.
To save it:
NSInteger myValue = ...; // This is your number
NSString *key = ... ; // This is a string to identify your number
[[NSUserDefaults standardUserDefaults] setInteger:myValue forKey:key];
To read it:
NSInteger myValue = [[NSUserDefaults standardUserDefaults] integerForKey:key];
If no previous value has been saved, the value returned will be 0.
Add this to your applicationWillTerminate:
[[NSUserDefaults standardUserDefaults] synchronize];
you can use the NSUserDefaults to store some variable for your application to retrieve them after a close of the application.
For exemple:
// Set the name of the view
[[NSUserDefaults standardUserDefaults] setInteger:10 forKey:#"firstValue"];
To retrieve the last action of the user:
// Retrieve the last view name
Integer firstValue = [[NSUserDefaults standardUserDefaults] integerForKey:#"firstValue"];
But you can add other than a integer. (see the NSUserDefaults Class Reference)