Array within a NSDictionary: how to save to the NSUserDefaults - iphone

I would like to save Array/NSDictionary to NSUserDefaults but anything I try is just not working. Here is my code so please if you know how to do this, help me.
NSArray *oneArray = [NSArray arrayWithObjects:#"Radio One",nil];
NSDictionary *one = [NSDictionary dictionaryWithObject:oneArray forKey:#"Stations"];
NSArray *oneLinkArray = [NSArray arrayWithObjects:#"http://mobile.com:28000/",nil];
NSDictionary *oneLink = [NSDictionary dictionaryWithObject:oneLinkArray forKey:#"Stations"];
[data addObject:one];
[link addObject:oneLink];
The reason I need this is to put this station into favorites. So my thinking is to save these info in to NSUserDefaults and retrieve in favorites table.
Thanks and please any suggestion is welcomed and appreciated.

You can use something like this when you store everything into a dictionary
[[NSUserDefaults standardUserDefaults] setObject:link forKey:#"dictionary1"];
Or you can put everything into an array and store it like this
[[NSUserDefaults standardUserDefaults] setObject:data forKey:#"array1"];
You can access it again by using
NSDictionary * myDictionary = [[NSUserDefaults standardUserDefaults] dictionaryForKey:#"dictionary1"];

Typically adding an object into NSUserDefaults goes like this:
NSMutableDictionary *dictionaryToAdd = [[NSMutableDictionary alloc] init];
[dictionaryToAdd setObject:#"xyz" forKey:#"myKey"];
NSUserDefaults *myDefaults = [NSUserDefaults standardUserDefaults];
[myDefaults setObject:dictionaryToAdd forKey:#"someKey"];
[myDefaults synchronize];
A few things on your code above though - you're adding stuff into 'data' and 'link' but I don't see those in your code, so I'm assuming those arrays exist somewhere.
To sum it up - declare an NSUserDefaults object, set objects into it like an NSDictionary, and then synchronize it to save data.
Additional code as requested:
//You have an array named arrayToAdd that has already been created
NSUserDefaults *myDefaults = [NSUserDefaults standardUserDefaults];
[myDefaults setObject:arrayToAdd forKey:#"SomeKeyThatYouMakeUp"];
[myDefaults synchronize];
//You want to get the array out of NSUserDefaults
NSArray *mySavedArray;
NSUserDefaults *myDefaults = [NSUserDefaults standardUserDefaults];
mySavedArray = [myDefaults objectForKey:#"SomeKeyThatYouMakeUp"];

Related

Saving NSDictionary with NSMutableArray as a value to NSUserDefaults

I am storing UIImage in NSMutableArray then storing NSMutableArray into NSDictionary.
Key of NSDictionary is a foldername and value of NSDictionary is a NSMutableArray.
Now how can i store and retrieve NSDictionary in NSUserDefaults.
I have done as follows:
NSMutableArray *imageArray=[[NSMutableArray alloc] init];
[imageArray addObject:selectedImage];
[allFolderWithImageDict setValue:imageArray forKey:#"UniqueFolderName"];
NSUserDefaults *defauktCenter = [NSUserDefaults standardUserDefaults];
[defauktCenter setValue:allFolderWithImageDict forKey:#"FolderImageDict"];
[defauktCenter synchronize];
But NSDictionary is not saving in NSUserDefaults.
Please suggest with some example
thanks
To Store and Retrieve Values of Custom Objects, you can use NSKeyedArchiver and NSKeyedUnarchiver Classes :
// To Save. . .
NSData *resData = [NSKeyedArchiver archivedDataWithRootObject:allFolderWithImageDict];
[[NSUserDefaults standardUserDefaults] setObject:resData forKey:#"FolderImageDict"];
// To Load. . .
NSData *respData = [[NSUserDefaults standardUserDefaults] objectForKey:#"FolderImageDict"];
resultDictionary = [NSKeyedUnarchiver unarchiveObjectWithData:respData];
NSLog(#"dict :: %#",resultDictionary);
GoodLuck !!!
To store UIImage objects in NSUserDefaults you need to a category implementation for UIImage that implements NSCoding protocol
here is one:
https://code.google.com/p/iphonebits/source/browse/trunk/src/Categories/UIImage-NSCoding.h
https://code.google.com/p/iphonebits/source/browse/trunk/src/Categories/UIImage-NSCoding.m
from
http://iphonedevelopment.blogspot.it/2009/03/uiimage-and-nscoding.html
Instead of using NSDictionary, use NSMutableDictionary.... :)
And to retrieve the data stored in dictionary.....
NSUserDefaults *d = [NSUserDefaults standardUserDefaults];
NSString *loadname1 = [d objectForKey:#"FolderImageDict"];
NSLog(#"%#", loadname1);

Can we update the array stored in NSUserDefault

I am having values stored in an array, and stored that array in NSUserDefault, then i need to update that array can i do so. If then how?
First retrieve the current data.
NSArray *tempNew = [[NSArray alloc]init];
tempNew = [storeData objectForKey:#"accounts"];
[tempArr addObjectsFromArray:tempNew];
Update:
[tempArr addObject:str];
[storeData setObject:tempArr forKey:#"accounts"];
NSUserDefaults is just as an NSDictionary, so you can use the same method of updating a dictionary by setting another object to the key value -setObject:forKey:.
for example when you try below code
NSUserDefaults *usr=[NSUserDefaults standardUserDefaults];
NSArray *arr= [NSArray arrayWithObjects:[NSNumber numberWithInt:1],[NSNumber numberWithInt:2], nil];
[usr setObject:arr forKey:#"num"];
NSLog(#"usr %#",[usr arrayForKey:#"num"]);
NSUserDefaults *usr1=[NSUserDefaults standardUserDefaults];
NSArray *arr= [NSArray arrayWithObjects:[NSNumber numberWithInt:2],[NSNumber
numberWithInt:3], nil];
[usr setObject:arr forKey:#"num"];
NSLog(#"user1 %#",[usr1 arrayForKey:#"num"]);
u will get
usr (
1,
2
)
usr1 (
2,
3
)
in console.
Just re-store the array in the user defaults and call synchronize.
So for example:
Store your array...
NSMutableArray *yourArray = .... // whatever you did to create your data
// store your data in the NSUserDefaults
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:yourArray forKey:#"myArray"];
[defaults synchronize];
... and then some other time somewhere in your app update it!
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
// retrieve your data from the NSUserDefaults
NSMutableArray *yourArray = [defaults objectForKey:#"myArray"];
// edit the data, for example add some object.
[yourArray addObject:someNewObject];
// update the defaults
[defaults setObject:yourArray forKey:#"myArray"];
[defaults synchronize];

NSUserDefaults, saving data issue

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

How to save / Load NSUserDefaults for backup purposes?

Is this code correct to load and save NSUserDefaults.
// Load
NSDictionary *dict = [[NSUserDefaults standardUserDefaults]
dictionaryRepresentation];
// Save
NSDictionary *dict = ....
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults registerDefaults:dict];
[defaults synchronize]; << Not sure if this is needed
I'm using JSON to hold the dictionary contents and I'm having problems.
I'd just like to know if this code is correct, before I look elsewhere for my problem.
Your Load code will get you a dictionary of all the current default values.
[Note This will probably be much larger than you expect as Mac OS installs a raft of defaults, you might want to make it smaller. For example, you can limit the dictionary to just those defaults in your domain which differ from their registered default using:
NSDictionary *userDefaults = [[NSUserDefaults standardUserDefaults] persistentDomainForName:#"<your bundle identifier>"];
end note]
Your Save code probably doesn't do what you expect, it installs the values you are restoring as the defaults for those keys - so if you support "Restore to Default Settings", or something similar, then these are the values that would result. What you probably want to do it set the current value of the keys, this can be done with a simple loop:
NSDictionary *dict = ....
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
foreach(id key in dict)
[defaults setObject:[dict objectForKey:key] forKey:key];
The above code is only an outline, you may need to take care what preferences you save/restore and in what order - but all that depends on your application.
// Get
NSDictionary *dict = [[NSUserDefaults standardUserDefaults] objectForKey:#"myDictionary"];
// Set
NSDictionary *dict = ...
[[NSUserDefaults standardUserDefaults] setObject:dict forKey:#"myDictionary"];

Use NSUserDefaults to access a stored object

I want to access text saved through NSUserDefaults and display it in a label that has already been defined called "name". My code is below, but it doesn't work. What should I do? Thanks for your help!
name = [[NSUserDefaults standardUserDefaults] objectForKey:#"Name"];
should be:
name.text = [[NSUserDefaults standardUserDefaults] objectForKey:#"Name"];
First, you should register your defaults someway like this: (this is only necessary if you want to add multiple items!)
NSDictionary *defaultsDict =
[NSDictionary dictionaryWithObjectsAndKeys:#"MyName", #"defaultName", #"MyAge", #"defaultAge", nil];`
[[NSUserDefaults standardUserDefaults] registerDefaults:defaultsDict];
Now use this assuming you have a label pointer:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[label setText:[defaults stringForKey:#"defaultName"]];