Storing preferences in NSUser Defaults to recall later - iphone

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: ...];

Related

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"];

Count and store a value in xcode

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....

Can I change the apps view based on if a file has been saved?

Please help! I'm a newbie to programming and I'm having the following trouble. I am trying to write my first iphone app and I would like it to do the following.
When the app launches user enters name, presses button and goes to new view. Their name is saved to file and used through out the app. That much I have managed.
I would like the app to check to see if there is a saved file when it is launched and go directly to second view instead of the first view. I'm have search for days looking for an answer and I'm still not sure how to do this.
At the risk of seeming stupid do I use an IF statement and how do I write it. Please help.
Thanking you in advance.
You have to use NSUserDefaults for storing the user name and pass words. If you want to store more data's, have to use plist(Documents Directory) or core data or SQLite.
// Store the data
[[NSUserDefaults standardUserDefaults] setObject:#"yourPasswordString" forKey:#"YourKey"];
// Retrieve the data
NSString *passWord = [[NSUserDefaults standardUserDefaults] objectForKey:#"YourKey"];
Once you retrieved the data, you have to check the conditions like,
if(passWord == nil)
{
//load first view
}
else
{
// load second view
}
Thanks!
if you're using NSUserDefaults to save it then all you have to do is try reading the value into a string, then check if it is nil, if it is, then the files isn't there and you would load your first view, if it was, then load your second view.
NSString *tempStr = [[NSUserDefaults standardUserDefaults] objectForKey:#"yourKey"];
if(tempStr == nil)
{
//load your first view
}
else
{
// load your second view
}
You need to read your key back out in order to test if it is nil, the way you are doing this, you will never be nil and will always use the else choice, you need to set your object elsewhere, probably in the if statement.
-(IBAction)LogInButton:(id)sender
{
NSString *tempStr = [[NSUserDefaults standardUserDefaults] objectForKey:#"UserName"];
if (tempStr == nil || [tempStr isEqualToString:""])
{
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:Name.text forKey:#"UserName"];
[prefs synchronize];
ClubSearchViewController *CSearch = [[ClubSearchViewController alloc]initWithNibName:#"ClubSearchViewController" bundle:Nil];
[self presentModalViewController:CSearch animated:YES];
}
else
{
SearchMenu *SMenu = [[SearchMenu alloc]initWithNibName:#"SearchMenu" bundle:nil];
[self presentModalViewController:SMenu animated:YES];
}
}
-(IBAction)LogOutButton:(id)sender
{
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:#"" forKey:#"UserName"];
[prefs synchronize];
}

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
}

NSUserDefaults doesn't save

i'm trying to save some informations in an iphone/ipad app.
The problem is that it works but if i close the app (with the home button on the simulator or closing with cmd+q) the informations become lost!
this is my code (and, if you see, i used "syncronize")
- (IBAction)choose1{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:#"choose1" forKey:#"choose"];
[defaults synchronize];
}
- (IBAction)choose2{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:#"choose2" forKey:#"choose"];
[defaults synchronize];
}
- (IBAction)openview{
NSString *var = [[NSUserDefaults standardUserDefaults] objectForKey:#"choose"];
if (var == #"choose1"){
[self pushViewController:view1 animated:YES];}
else if (var == #"choose2"){
[self pushViewController:view2 animated:YES];
}
}
I don't understand why :(
When comparing strings, you should use the isEqualToString method, ie:
if ([var isEqualToString:#"choose1"]){
Otherwise you are comparing actual objects rather than their contents.
I am not entirely sure, but maybe it is saving your defaults and the error is located somewhere else. I am thinking about your "openView" method:
- (IBAction)openview{
NSString *var = [[NSUserDefaults standardUserDefaults] objectForKey:#"choose"];
if (var == #"choose1"){
[self pushViewController:view1 animated:YES];}
/** you are comparing to "choose1" here as well. **/
else if (var == #"choose1"){
[self pushViewController:view2 animated:YES];
}
Another possibilty might be that you never call your choose1() or choose2() methods?
This would explain why the value is never changed.
Despite from these 2 possibilites I think there is no error in the code you use to change the UserDefaults.
Hope this helps.
Regards,
Gjallar
ah, i'm sorry: i'm italian so i used the word "choose" with the italian translation "scelta".
Here i translated in english and i wrote "choose1" but in my code i used "choose2" (or "scelta2" :P)
for the other possibility (that i've never called the function choose1() or choose2() )... no, i've called, of course!