Reputation: 1
So I have an app that lets you put in a title and an author on the front page, then you hit enter and it will go into the actual features of the app. I want to save the data with NSUserDefaults, so that when they click the enter button, it saves it *AND goes into the next view. I have it setup with the storybord already to go into the next view, but when I use this code:
-(IBAction)enter:(id)sender {
titleString = [[NSString alloc] initWithFormat:[title text]];
[title setText:titleString];
NSUserDefaults *titleDefault = [NSUserDefaults standardUserDefaults];
[titleDefault setObject:titleString forKey:@"stringkey"];
authorString = [[NSString alloc] initWithFormat:[author text]];
[title setText:authorString];
NSUserDefaults *authorDefault = [NSUserDefaults standardUserDefaults];
[authorDefault setObject:authorString forKey:@"stringkey2"];
}
It will always crash when you hit the button. I have all the NSStrings defined and such, so I don't see what the problem is. I also have it loading with:
title.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"stringkey"];
author.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"stringkey2"];
Under the viewdidload, so can I have some help as to why this wouldn't work?
Upvotes: 0
Views: 241
Reputation: 3588
Just to optimize your -enter:
method:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:title.text forKey:@"stringkey"];
[defaults setObject:author.text forKey:@"stringkey2"];
[defaults synchronize]; // this will store them instantly!
For the crash: can you please provide us with the exact crash log? Maybe your Button is linked to an unknown selector...
Upvotes: 1
Reputation: 4388
First, there are a few questions about this: here, here. Try searching around first, and at least let people know why the duplicate questions you found didn't work for you.
Secondly, I think you might benefit from adding a synchronize
. Use this:
titleString = [[NSString alloc] initWithFormat:[title text]];
[title setText:titleString];
NSUserDefaults *titleDefault = [NSUserDefaults standardUserDefaults];
[titleDefault setObject:titleString forKey:@"stringkey"];
[titleDefault synchronize];
authorString = [[NSString alloc] initWithFormat:[author text]];
[author setText:authorString];
NSUserDefaults *authorDefault = [NSUserDefaults standardUserDefaults];
[authorDefault setObject:authorString forKey:@"stringkey2"];
[authorDefault synchronize];
I also changed the [title setText:authorString];
line to [author setText:authorString];
. I do, however, think it is a bit redundant the way you are allocating the NSString
s to the value of the text fields and then setting the text back to the value of the string you created. I don't get the need. Anyway, hope this helps.
Upvotes: 0