How can we store into an NSDictionary? What is the difference between NSDictionary and NSMutableDictionary?
Asked Answered
G

3

67

I am developing an application in which I want to use an NSDictionary. Can anyone please send me a sample code explaining the procedure how to use an NSDictionary to store Data with a perfect example?

Gametocyte answered 19/11, 2009 at 1:34 Comment(3)
You could start by having a look at the NSDictionary documentation ...Sappanwood
The polite RTFMs somehow seem more caustic than the explicit ones.Ovotestis
@Sappanwood For a lot of new programmers official documentation is often very complicated and confusing so a basic view of x on SO helps out.Protectionist
D
191

The NSDictionary and NSMutableDictionary docs are probably your best bet. They even have some great examples on how to do various things, like...

...create an NSDictionary

NSArray *keys = [NSArray arrayWithObjects:@"key1", @"key2", nil];
NSArray *objects = [NSArray arrayWithObjects:@"value1", @"value2", nil];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:objects 
                                                       forKeys:keys];

...iterate over it

for (id key in dictionary) {
    NSLog(@"key: %@, value: %@", key, [dictionary objectForKey:key]);
}

...make it mutable

NSMutableDictionary *mutableDict = [dictionary mutableCopy];

Note: historic version before 2010: [[dictionary mutableCopy] autorelease]

...and alter it

[mutableDict setObject:@"value3" forKey:@"key3"];

...then store it to a file

[mutableDict writeToFile:@"path/to/file" atomically:YES];

...and read it back again

NSMutableDictionary *anotherDict = [NSMutableDictionary dictionaryWithContentsOfFile:@"path/to/file"];

...read a value

NSString *x = [anotherDict objectForKey:@"key1"];

...check if a key exists

if ( [anotherDict objectForKey:@"key999"] == nil ) NSLog(@"that key is not there");

...use scary futuristic syntax

From 2014 you can actually just type dict[@"key"] rather than [dict objectForKey:@"key"]

Disinfection answered 19/11, 2009 at 1:40 Comment(0)
N
32
NSDictionary   *dict = [NSDictionary dictionaryWithObject: @"String" forKey: @"Test"];
NSMutableDictionary *anotherDict = [NSMutableDictionary dictionary];

[anotherDict setObject: dict forKey: "sub-dictionary-key"];
[anotherDict setObject: @"Another String" forKey: @"another test"];

NSLog(@"Dictionary: %@, Mutable Dictionary: %@", dict, anotherDict);

// now we can save these to a file
NSString   *savePath = [@"~/Documents/Saved.data" stringByExpandingTildeInPath];
[anotherDict writeToFile: savePath atomically: YES];

//and restore them
NSMutableDictionary  *restored = [NSDictionary dictionaryWithContentsOfFile: savePath];
Navigator answered 19/11, 2009 at 1:39 Comment(2)
@Ben Gottlieb Part One: Thanks for nice explanations. Actually i want to save two of my UItextField data in a file from MutableDictionary. Here you wrote NSString *savePath = [@"~/Documents/Saved.data" stringByExpandingTildeInPath];, now my question is, what is the Saved.data file here? How can i made it?Ripley
@Ben Gottlieb Part Two: And in my case i put a text file (.rtf) in the following directory Supporting files > MediaFiles > Documents > userData.rtf.Now can i save these type of Mutabledictionary data in text file? And what will be the perfect directory in this case? I was trying with this [userData writeToFile:@"MediaFiles/Documents/userData.rtf" atomically:YES]; & with this [userData writeToFile:@"Documents/userData.rtf" atomically:YES];, but didn't work. Have a good day.Ripley
G
18

The key difference: NSMutableDictionary can be modified in place, NSDictionary cannot. This is true for all the other NSMutable* classes in Cocoa. NSMutableDictionary is a subclass of NSDictionary, so everything you can do with NSDictionary you can do with both. However, NSMutableDictionary also adds complementary methods to modify things in place, such as the method setObject:forKey:.

You can convert between the two like this:

NSMutableDictionary *mutable = [[dict mutableCopy] autorelease];
NSDictionary *dict = [[mutable copy] autorelease]; 

Presumably you want to store data by writing it to a file. NSDictionary has a method to do this (which also works with NSMutableDictionary):

BOOL success = [dict writeToFile:@"/file/path" atomically:YES];

To read a dictionary from a file, there's a corresponding method:

NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:@"/file/path"];

If you want to read the file as an NSMutableDictionary, simply use:

NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithContentsOfFile:@"/file/path"];
Gypsophila answered 19/11, 2009 at 1:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.