¿Cómo podemos almacenar en un NSDictionary? ¿Cuál es la diferencia entre NSDictionary y NSMutableDictionary?


Estoy desarrollando una aplicación en la que quiero usar un NSDictionary. ¿Puede alguien por favor enviarme un código de ejemplo explicando el procedimiento cómo usar un NSDictionary para almacenar Datos con un ejemplo perfecto?

Author: Atulkumar V. Jain, 2009-11-19

3 answers

Los documentos NSDictionary y NSMutableDictionary son probablemente su mejor opción. Incluso tienen algunos grandes ejemplos de cómo hacer varias cosas, como...

...crear un NSDictionary

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

...iterar sobre él

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

...que sea mutable

NSMutableDictionary *mutableDict = [dictionary mutableCopy];

Nota: versión histórica antes de 2010: [[dictionary mutableCopy] autorelease]

...y alter it

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

...luego guárdelo en un archivo

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

...y leerlo de nuevo

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

...leer un valor

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

...compruebe si existe una clave

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

...use sintaxis futurista aterradora

A partir de 2014 puedes escribir dict[@"key"] en lugar de [dict objectForKey:@ "key"]

 191
Author: Tim,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-04-16 13:29:17
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];
 32
Author: Ben Gottlieb,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-11-19 01:39:54

La diferencia clave: NSMutableDictionary se puede modificar en su lugar, NSDictionary no puede. Esto es cierto para todas las otras clases NSMutable* en Cocoa. NSMutableDictionary es una subclase de NSDictionary, por lo que todo lo que puedes hacer con NSDictionary lo puedes hacer con ambos. Sin embargo, NSMutableDictionary también agrega métodos complementarios para modificar cosas en su lugar, como el método setObject:forKey:.

Puede convertir entre los dos de esta manera:

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

Presumiblemente quieres para almacenar datos escribiéndolos en un archivo. NSDictionary tiene un método para hacer esto (que también funciona con NSMutableDictionary):

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

Para leer un diccionario de un archivo, hay un método correspondiente:

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

Si desea leer el archivo como un NSMutableDictionary, simplemente use:

NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithContentsOfFile:@"/file/path"];
 18
Author: jtbandes,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-11-19 01:41:07