NSUserDefaults Arrays - objective-c

I need two NSMutableArray that will contain NSString.
These arrays are:
ListOFUserNames=[NSMutableArray array];
SituationstoName =[NSMutableArray array];
I have two different sets of strings that go into each mutable array.
After named gets added to Listofusernames
Situation gets added to SituationstoName
[ListOFUserNames addObject:AfterNamed];
[SituationstoName addObject:Situation];
I am trying to save listofusernames and situationstoname with their respective strings.
NSUserDefaults *something = [NSUserDefaults standardUserDefaults];
[something setObject:ListOFUserNames forKey:#"somedata"];
[something synchronize];
NSUserDefaults *something2 = [NSUserDefaults standardUserDefaults];
[something2 setObject:SituationstoName forKey:#"somedata2"];
[something2 synchronize];
In the method that loads them, nothing comes out.
The code for that method is:
NSUserDefaults *somet = [NSUserDefaults standardUserDefaults];
NSUserDefaults *somet2 = [NSUserDefaults standardUserDefaults];
ListOFUserNames = [somet objectForKey:#"somedata"] ;
SituationstoName = [somet2 objectForKey:#"somedata2"] ;
[somet synchronize];
[somet2 synchronize];
The problem is that it is not loading the strings that are saved in the mutable arrays.

//initialise array
NSMutableArray *listOFUserNames=[[NSMutableArray alloc] init];
NSMutableArray *situationstoName =[[NSMutableArray alloc] init];
//add content in the array
[listOFUserNames addObject:AfterNamed];
[situationstoName addObject:Situation];
(Before storing also check if your array contains objects or is empty.)
//Store these array in `NSUserDefaults`
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setObject:listOFUserNames forKey:#"NameData"];
[userDefaults setObject:situationstoName forKey:#"SituationData"];
[userDefaults synchronize];
//Access data where ever you want to be
//(listOFUserNames and situationstoName must be array)
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
listOFUserNames = [userDefaults objectForKey:#"NameData"] ;
situationstoName = [userDefaults objectForKey:#"SituationData"] ;

Related

How to save fields correctly with NSUserDefaults?

I'm creating a program that saves a String from one text field and an integer from a second text field. I am trying to use NSUserDefaults, but I can't seem to get either of them to save correctly when I run the program. It crashes when I press the save button with the breakpoint while handling the NSUserDefaults. Am I doing something wrong? I skimmed through the documentation, but it didn't help. Can I even use 2 different instances of NSUserDefaults?
- (IBAction)save:(id)sender {
//Save stuff fropm textfields
NSString* name = _nameText.text;
int count = [_countText.text intValue];
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
[[NSUserDefaults standardUserDefaults] setObject:name forKey:#"name"];
[[NSUserDefaults standardUserDefaults] setInteger:count forKey:#"count"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
- (IBAction)load:(id)sender {
//Load stuff from NSUserDefaults
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
NSString* loadstring = [defaults objectForKey:#"name"];
_nameText.text = loadstring;
NSUserDefaults* defaults2 = [NSUserDefaults standardUserDefaults];
NSInteger loadint = [defaults2 integerForKey:#"count"];
_countText.text = [NSString stringWithFormat:#"%li", (long)loadint];
}
Declare defaults = [NSUserDefaults standardDefaults]; in your viewDidLoad (and NSUserDefaults* defaults; in .h) and use this code:
- (IBAction)save:(id)sender {
//Save stuff fropm textfields
NSString* name = _nameText.text;
int count = [_countText.text intValue];
[defaults setObject:name forKey:#"name"];
[defaults setInteger:count forKey:#"count"];
[defaults synchronize];
}
- (IBAction)load:(id)sender {
//Load stuff from NSUserDefaults
_nameText.text = [defaults stringForKey:#"name"];
_countText.text = [NSString stringWithFormat:#"%li", (long)[defaults integerForKey:#"count"]];
}

If statement in NSUserDefault when loading a string

I have the following code for saving a value and an string. I want to use If statement to check my value.
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:#"Baseball bat" forKey:#"Weaponsname"];
NSInteger Attack1 = [defaults integerForKey:#"Attack"];
NSString *Weapon = [defaults stringForKey:#"Weaponsname"];
if([Weapon isEqual: #"Baseball bat"]){
[defaults setInteger:(Attack1+50) forKey:#"Attack"];
NSLog(#"Baseball bat");
}
[defaults synchronize];
So if i have the Baseball bat, the Attack should increase by 50. But it doesn't.
What wrong with the code?
Thanks
For string comparison you should use the isEqualToString method found in the NSString class.
if ([Weapon isEqualToString:#"Baseball bat"]) { ... }

Save value of the variable

Here is the NSUserdefaults code.
-(IBAction)SaveButton:(id)sender {
NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
NSString* Assignment0Text = screen0.text;
[defaults setObject:Assignment0Text forKey:#"Assignment0Text"];
[defaults synchronize];
}
-(IBAction)LoadButton:(id)sender {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString* temp0 = [defaults objectForKey:#"Assignment0Text"];
screen0.text = temp0;
}
This code above means that the program only saves and loads the string value inside the textfield/label.
My question is, how can I modify this code so that the NSUserDefaults can save and load the value of a variable (in this case int & float), not the text inside the textfield/label? So that when I load the program, all the integer/float values are the same. Not what's written in the text inside the textfield/label are the same. All that the screen is showing is a float number with variable called runningtotal.
screen0.text = [NSString stringWithFormat:#"%2.2f", runningtotal];
if I understand your question correctly, you should use wrappers for variables like int:
int value = 5;
[defaults setObject:#(value) forKey:#"Assignment0Number"];
the magic is the NSUserDefaults can not store non-object values like 5. You need to create NSObject object, store the value within it, and then save this object into the NSUserdefaults. That is what happens when I write '#(value)'.
If to be more precise, #(value) is literal for [NSNumber numberWithInt:value], and since NSNumber is the object and subclass of NSObject, the value can be stored now.
EDIT:
here is what you probably want (I assume that runningtotal is the class variable):
-(IBAction)SaveButton:(id)sender {
NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
[defaults setObject:#(runningtotal) forKey:#"Assignment0Text"];
[defaults synchronize];
}
-(IBAction)LoadButton:(id)sender {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSNumber* temp0 = [defaults objectForKey:#"Assignment0Text"];
runningtotal = [temp0 intValue];
}

NSUserDefaults not saving in table cell

When I replace the #"hello" with titlestring the table, the cell shows up blank, If i leave the hello, everything works, including the "detailsstring". I don't know why it's doing that since detailsstring is set up exactly the same as titlestring.
here is the code:
in the .m file I have
#synthesize detailsstring;
#synthesize titlestring;
and it's all defined the same in the .h in the .m I have this as well:
- (void)viewDidLoad{
titlestring =[[NSUserDefaults standardUserDefaults] objectForKey:#"titletext"];
detailsstring = [[NSUserDefaults standardUserDefaults] objectForKey:#"details"];
tabledata = [[NSArray alloc] initWithObjects:#"hello", nil];
tablesubtitles = [[NSArray alloc] initWithObjects:detailsstring, nil];
[super viewDidLoad];
}
Now, I'm saving those Userdefaults in another controller. Here is the save button action in a different view controller:
- (IBAction)saveButton:(id)sender {
NSUserDefaults *titletext = [NSUserDefaults standardUserDefaults];
[titletext setObject:titleTextfield.text forKey:#"titletext"];
NSUserDefaults *details = [NSUserDefaults standardUserDefaults];
[details setObject:detailstextfield.text forKey:#"details"];
NSUserDefaults *categoryUser = [NSUserDefaults standardUserDefaults];
[categoryUser setInteger:selectedCategory forKey:#"category"];
}
What am I doing wrong?
First of all, one instance of NSUserDefaults is sufficient for all three modifications. To 'push' the changes to the file system immediately, you can call [userDefaults synchronize];. Otherwise there is no guarantee that your changes are saved instantly. Apple suggests only to call this method if you cannot wait for the changes to be saved.
- (IBAction)saveButton:(id)sender {
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setObject:titleTextfield.text forKey:#"titletext"];
[userDefaults setObject:detailstextfield.text forKey:#"details"];
[userDefaults setInteger:selectedCategory forKey:#"category"];
[userDefaults synchronize];
}
In your viewDidLoad: method, try to output the saved values to test your application's integrity:
NSLog(#"%#", [[NSUserDefaults standardUserDefaults] objectForKey:#"details"]);

NSUserDefaults will not load after leaving app

I set up multiple NSUserDefaults in my app that work for the most part. The NSUserDefaults are called from one ViewController and implemented at another (such as in a game with a level select). This seems to work well, until the user presses the back button on the level select screen. When they try to go back to the level select viewController, the NSUserDefaults are not loaded onto the screen.
Here is my code:
LevelSelectViewController:
- (void)viewDidLoad
{
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults synchronize];
[super viewDidLoad];
}
- (void)Level1DidFinish:(Level1 *)controller
{
[self dismissModalViewControllerAnimated:YES];
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSInteger rank = [userDefaults integerForKey:#"levelRank"];
{
if (rank == 1) {
button2.hidden = NO;
}
}
}
Level1ViewController:
{
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setInteger:1 forKey:#"levelRank"];
}
You need to call [userDefaults synchronize] after setting a value for a key. The automatic synchronization happens quite rarely, so in this case, while one completes a level, the sync won't have yet happened.
So modify your code like this:
Level1ViewController:
{
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setInteger:1 forKey:#"easyRank"];
[userDefaults synchronize];
}
Your first issue is you are creating an instance of userDefaults, but are not setting any values. So calling synchronize here is actually doing nothing:
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults synchronize];
After you set a your Integer, then you need to call synchronize:
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setInteger:1 forKey:#"easyRank"];
[userDefaults synchronize];
You're setting values for two different keys. What are you expecting to happen?
Either Level1ViewController needs to set a value for levelRank or LevelSelectViewController needs to read the value for the easyRank key.