NSDictionary Inside An NSDictionary - iphone

I have the following code:
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSMutableDictionary *golferIconsu = [userDefaults objectForKey:#"golferIconsFirstScene"];
NSMutableDictionary *golferIconsSceneOne = [[NSMutableDictionary alloc]initWithDictionary:golferIconsu];
NSMutableDictionary *savedScoreCards;
NSMutableDictionary *currentScoreCard;
[currentScoreCard setObject:golferIconsSceneOne forKey:#"golferIconsFirstScene"];
NSMutableDictionary *GI = [currentScoreCard objectForKey:#"golferIconsFirstScene"];
[savedScoreCards setObject:currentScoreCard forKey:#"1"];
NSLog([golferIconsSceneOne objectForKey:#"30101"]);
NSLog([GI objectForKey:#"30101"]);
At the end all that is printed out in my log is the first NSLog call, not the second one. For example:
NSLog([golferIconsSceneOne objectForKey:#"30101"]);
This prints out a string that I stored in that dictionary.
This one:
NSLog([GI objectForKey:#"30101"]);
Doesn't print out anything at all.
How can I get the NSDictionary GI to have the exact same properties as golferIconsSceneOne, but I need to do this using the currentScoreCardDictionary, which contains golferIconsSceneOne?

Initialise your dictionary before setting object in it.
NSMutableDictionary *savedScoreCards = [[NSMutableDictionary alloc] init];
NSMutableDictionary *currentScoreCard = [[NSMutableDictionary alloc] init];

Do like this intialize one and set it into other
NSMutableDictionary *savedScoreCards = [[NSMutableDictionary alloc] init];
NSMutableDictionary *currentScoreCard = [[NSMutableDictionary dictionaryWithDictionary:savedScoreCards];

Related

NSUserDefaults display date and data in the tableView

In the FirstViewController of my survey app I have NSMutableArray that contains data (strings). I've also created date varibale. Here's code
NSDateFormatter *dateformater=[[NSDateFormatter alloc] init];
[dateformater setDateFormat:#"EEEE,dd MMMM yyyy HH:mm a"];
NSDate *today=[NSDate date];
NSString *currentDate=[dateformater stringFromDate:today];
Now I want with the help of NSUserDefaults save data from the array and also save date variable when the survey has been taken and display it in the SecondViewController's tableview (first user can see date of the survey and then by tapping the date - data from array).
I know how NSUSerDefaults work but I don't know how to put array by date variable to be shown in the SecondViewController. Can anyone help me on that?
In AppDelegate.h file just declare variable...
NSUserDefaults *userDefaults;
NSMutableArray *arrDate;
after...
In AppDelegate.m Fille in applicationDidFinishLonching: Method
userDefaults = [NSUserDefaults standardUserDefaults];
NSData *dataRepresentingtblArrayForSearch = [userDefaults objectForKey:#"arrDate"];
if (dataRepresentingtblArrayForSearch != nil) {
NSArray *oldSavedArray = [NSKeyedUnarchiver unarchiveObjectWithData:dataRepresentingtblArrayForSearch];
if (oldSavedArray != nil)
arrDate = [[NSMutableArray alloc] initWithArray:oldSavedArray];
else
arrDate = [[NSMutableArray alloc] init];
} else {
arrDate = [[NSMutableArray alloc] init];
}
[arrDate retain];
after that when you want to insert,update or delete Data from this UserDefaults Use Bellow Code...
for Delete record from array
[appDelegate.arrDate removeObjectAtIndex:Index];/// give the integer value instead of Index
and this is for add record in array..
[appDelegate.arrDate addObject:currentDate];///add value or add date here
after in final save this modification in array just archive like bellow..
NSData *data=[NSKeyedArchiver archivedDataWithRootObject:appDelegate.arrDate];
[appDelegate.userDefaults setObject:data forKey:#"arrDate"];
[appDelegate.userDefaults synchronize];
Create a NSDictionary with the date and data object:
NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:[NSString stringWithFormat:#"%#",currentDate], #"date", #"yourData", #"data", nil];
Then put it in the NSUserDefault using:
[NSUserDefaults standardUserDefaults] setObject:yourDictionary forKey:#"item1"];
This will store a single data to NSUserDefault.
You can retrieve the object by using:
NSDictionary * dictionary = [[NSUserDefaults standardUserDefaults] dictionaryForKey:#"item1"];
Now you will get the date using [dictionary objectForKey:#"date"]; and data using : [dictionary objectForKey:#"data"];

NSDictionary Not Storing Information

For some weird reason golferStats is not storing info correctly...
I cut out a bunch of stuff in this code to the bare basics why is is still not working?
Problem: The last NSLOG returns nil when it should return a huge array...
NSMutableDictionary *golferStats = [[NSMutableDictionary alloc] init];
golferStats = [userDefaults objectForKey:#"golferStats"];
[golferStats setObject:golferTwoIconCounter forKey:golferName]; //golferName is k
[userDefaults setObject:golferStats forKey:#"golferStats"];
[userDefaults synchronize];
NSLog(#"SAVED SCORE CARD");
NSLog(#"%#",[golferStats objectForKey:#"k"]);
NSMutableDictionary *golferStats = [[NSMutableDictionary alloc] init];
golferStats = [userDefaults objectForKey:#"golferStats"];
...
[golferStats release];
You first create an NSDictionary and then you assign over top of it, thus leaking memory and presumably getting nil back from user defaults. setObject:forKey: in the nil dictionary is a no-op, and then you are setting it back into the user defaults.
EDIT:
Try checking if there is a dictionary first:
NSDictionary *golferStats = [userDefaults objectForKey:#"golferStats"];
if (golferStats == nil) {
golferStates = [NSDictionary dictionary]; // this will not leak
}
...
If you want to preserve the existing contents of the dictionary in cases where it already does exist, do this:
NSMutableDictionary *golferStats = [userDefaults objectForKey:#"golferStats"];
if (!golferStats) golferStats = [[[NSMutableDictionary alloc] init] autorelease];
[golferStats setObject:golferTwoIconCounter forKey:golferName];
[userDefaults setObject:golferStats forKey:#"golferStats"];
[userDefaults synchronize];
// no [golferStats release] because of autorelease above

Objective C - UserDefaults Over Writing

I can't seem to re edit this object in my ios User Defaults. Here is my code...
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setObject:nil forKey:#"savedScoreCards2"];
Before I did this I set the key savedScoreCards to a huge 3-d dictionary, and now when I try to over write it or even set the key to nil that huge 3-d dictionary that I set up a while ago is still there. I can't seem to over write/ replace it will nothing (nil), or another huge 3-d dictionary. Any ideas?
UPDATE:
+ (void)saveCurrentScoreCard
{
//save score card
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSMutableDictionary *savedScoreCards = [[NSMutableDictionary alloc] init];
[userDefaults setObject:nil forKey:#"savedScoreCards2"];//reset at beginning
NSMutableArray *golferOneScoresu = [userDefaults arrayForKey:#"golferOneScoresArray"];
NSMutableArray *golferTwoScoresu = [userDefaults arrayForKey:#"golferTwoScoresArray"];
NSMutableDictionary *golferIconsu = [userDefaults objectForKey:#"golferIconsFirstScene"];
NSMutableArray *golferThreeScoresu = [userDefaults arrayForKey:#"golferThreeScoresArray"];
NSMutableArray *golferFourScoresu = [userDefaults arrayForKey:#"golferFourScoresArray"];
NSMutableDictionary *golferIcons2u = [userDefaults objectForKey:#"golferIcons"];
NSMutableArray *golferNamesu = [userDefaults objectForKey:#"golferNames"];
NSMutableArray *golferNames = [[NSMutableArray alloc] initWithArray:golferNamesu copyItems:YES];
NSMutableDictionary *golferIconsSceneOne = [[NSMutableDictionary alloc]initWithDictionary:golferIconsu];
NSMutableDictionary *golferIcons = [[NSMutableDictionary alloc]initWithDictionary:golferIcons2u];
NSMutableArray *golferFourScores = [[NSMutableArray alloc] initWithArray:golferFourScoresu copyItems:YES];
NSMutableArray *golferThreeScores = [[NSMutableArray alloc] initWithArray:golferThreeScoresu copyItems:YES];
NSMutableArray *golferOneScores = [[NSMutableArray alloc] initWithArray:golferOneScoresu copyItems:YES];
NSMutableArray *golferTwoScores = [[NSMutableArray alloc] initWithArray:golferTwoScoresu copyItems:YES];
NSMutableDictionary *currentScoreCard = [[NSMutableDictionary alloc] init];
[currentScoreCard setObject:golferNames forKey:#"golferNames"];
[currentScoreCard setObject:golferIconsSceneOne forKey:#"golferIconsFirstScene"];
[currentScoreCard setObject:golferIcons forKey:#"golferIcons"];
[currentScoreCard setObject:golferOneScores forKey:#"golferOneScoresArray"];
[currentScoreCard setObject:golferTwoScores forKey:#"golferTwoScoresArray"];
[currentScoreCard setObject:golferThreeScores forKey:#"golferThreeScoresArray"];
[currentScoreCard setObject:golferFourScores forKey:#"golferFourScoresArray"];
[savedScoreCards setObject:currentScoreCard forKey:#"1"];
NSLog([golferIconsSceneOne objectForKey:#"30101"]);
[userDefaults setObject:savedScoreCards forKey:#"savedScoreCards2"];
[userDefaults synchronize];
NSLog(#"SAVED SCORE CARD");
}
Use [userDefaults removeObjectForKey:#"savedScoreCards2"] if you're just trying to remove a stored value.
Also call [userDefaults synchronize]; to "flush" your changes immediately. I think the [userDefaults synchronize] is probably what you're missing.
NSUserDefaults do not save automatically when you make a change to them. Try adding this line below the ones you've posted above:
[userDefaults synchronize];
This should save any changes you've made.
As a side note, I'm not sure you can save 'nil' into NSUserDefaults; at its core I believe it's a dictionary, in which nil values cannot be set. So you might try setting an empty object, instead.
Hope this helps, let me know if you need any more information!

Replace a value in NSDictionary in iPhone

I have a array (dataArray) of NSDictionary "item". It has datas like "david" for key "name" and "85" for key "marks" etc for 5 students. I want to replace the mark of david to 90 with respect to the array index value (ie 0 for dictionary containing david and 85). How can I do it?
The code for content in array is
[item setobject:name forkey:#"Name"];
[item setobject:mark forkey:#"Marks"];
[dataArray addOject:item]
The above code goes inside parsing, so i have array with 5 objects (students), their name and marks, now I want to replace the mark of the first object in the dataArray.
Here's what you can do:
NSMutableDictionary *newDict = [[NSMutableDictionary alloc] init];
NSDictionary *oldDict = (NSDictionary *)[dataArray objectAtIndex:0];
[newDict addEntriesFromDictionary:oldDict];
[newDict setObject:#"Don" forKey:#"Name"];
[dataArray replaceObjectAtIndex:0 withObject:newDict];
[newDict release];
Hope this helps!
You first need an NSMutableDictionary with it you can change the key and value.
It would be like this:
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:#"david", #"name", "85", #"marks", nil];
[dict setObject:#"90" forKey:#"david"];
// NSDictionary *dict = ...
NSMutableDictionary *mutableDict = [dict mutableCopy];
[mutableDict setObject:#"myObject" forKey:#"myKey"];
dict = [mutableDict mutableCopy];
I hope it helps
If you want to update an object in a NSDictionary you should use NSMutableDictionary instead.
NSMutableDictionary has the following EXTRA methods
Adding Entries
setObject:forKey:
setValue:forKey:
addEntriesFromDictionary:
setDictionary:
Removing Entries
removeObjectForKey:
removeAllObjects
removeObjectsForKeys:
[davidsRecord setObject:#"100" forkey:#"mark"];

Using objective-c objects with an NSDictionary

I want store a URL against a UILabel so that when a user touches the label it takes them to that URL in a UIWebView.
I have declared a NSDictionary like so:
NSMutableArray *linksArray = [[NSMutableArray alloc] init];
[linksArray addObject: [NSValue valueWithNonretainedObject: newsItem1ReadMoreLabel]];
[linksArray addObject: [NSValue valueWithNonretainedObject: newsItem2ReadMoreLabel]];
[linksArray addObject: [NSValue valueWithNonretainedObject: newsItem3ReadMoreLabel]];
[linksArray addObject: [NSValue valueWithNonretainedObject: newsItem4ReadMoreLabel]];
[linksArray addObject: [NSValue valueWithNonretainedObject: newsItem5ReadMoreLabel]];
//NSString *ageLink = #"http://www.theage.com.au";
NSArray *defaultLinks = [NSArray arrayWithObjects: #"1", #"2", #"3", #"4", #"5", nil];
self.urlToLinkDictionary = [[NSMutableDictionary alloc] init];
self.urlToLinkDictionary = [NSDictionary dictionaryWithObjects:defaultLinks forKeys:linksArray];
Considering I used a NSValue as the key, how do I get/set the URL associated with that key given that I only have references to the UILabels?
this is what I have but it doesn't work:
for(NSValue *key in [self.urlToLinkDictionary allKeys])
{
if ([key nonretainedObjectValue] == linkedLabel)
{
[self.urlToLinkDictionary setValue:[newsItem link] forKey: key];
}
}
but I get an error: "objc_exception_throw" resolved
These two lines are the cause of the issue:
self.urlToLinkDictionary = [[NSMutableDictionary alloc] init];
self.urlToLinkDictionary = [NSDictionary dictionaryWithObjects:defaultLinks forKeys:linksArray];
First you assign a mutable array to the property. Then you assign a different immutable array to the property. Your original mutable array leaks because you don't release it.
The exception is being caused by this line:
[self.urlToLinkDictionary setValue:[newsItem link] forKey: key];
By the time you get to it, self.urlToLinkDictionary is an immutable dictionary. You can't change it.
There are other problems:
linksArray leaks because you never release it.
newsItem1ReadMoreLabel etc. What type are they? Why are you wrapping them in values?
setValue:forKey: is part of key value coding. On a mutable dictionary it works, but the correct method for accessing objects by keys is setObject:forKey:
it seems a bit pointless to search a dictionary by doing a linear search through its keys.
Why not try a more simplified approach. Associate a tag with every label. The tag is a in integer value and you can use it to locate the url in an array.
So code for creating the array.
NSMutableArray* arrayURLs = [NSMutableArray arrayWithCapacity:2];
newsItem1ReadMoreLabel.tag = 0;
[arrayURLs insertObject:urlStringforLabel1 atIndex:newsItem1ReadMoreLabel.tag];
newsItem2ReadMoreLabel.tag = 1;
[arrayURLs insertObject:urlStringforLabel2 atIndex:newsItem2ReadMoreLabel.tag];
then you can access the urlstring for the appropriate label
NSString* url = [arrayURLs objectAtIndex:labelClicked.tag];