¿NSDictionary a NSArray?


Tengo un NSDictionary que se parece a:

{
"Item1" = 2.4;
"Item2" = 5.5;
"Item3" = 15.6;
}

Para usar estos elementos NSDictionary en una Vista de tabla tengo que transferirlos a un NSArray, ¿tengo razón?

Así que intento:

NSDictionary *dict = [myDict objectForKey:@"items"];

for (id item in dict) {
    [_myArray addObject:[dict objectForKey:item]];
}

Pero _myArray se mantiene vacío? ¿Qué estoy haciendo mal?

Author: John Conde, 2010-02-16

11 answers

Dejando de lado los problemas técnicos con el código que publicaste, preguntaste esto:

Para usar este Diccionario en una Vista de tabla tengo que transferirlo a un NSArray, ¿tengo razón?

La respuesta a la cual es: no necesariamente. No hay nada intrínseco a la maquinaria de UITableView, UITableViewDataSource, o UITableViewDelegate eso significa que sus datos tienen que estar en una matriz. Tendrá que implementar varios métodos para decirle al sistema cuántas filas hay en su tabla y qué datos aparece en cada fila. Muchas personas encuentran mucho más natural y eficiente responder a esas preguntas con una estructura de datos ordenada como una matriz. Pero no hay requisito que lo hagas. Si puede escribir el código para implementar esos métodos con el diccionario con el que comenzó, ¡siéntase libre!

 29
Author: Sixten Otto,
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
2010-02-16 16:14:12
NSArray * values = [dictionary allValues];
 221
Author: Dave DeLong,
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
2010-02-16 16:04:36
NSArray *keys = [dictionary allKeys];
NSArray *values = [dictionary allValues];
 43
Author: Nikhil Dinesh,
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
2013-08-01 11:07:48

Puede crear una matriz de todos los objetos dentro del diccionario y luego usarla como fuente de datos para la vista de tabla.

NSArray *aValuesArray = [yourDict allValues];
 5
Author: RandomGuy,
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-02-14 11:33:15

Fragmento de código 1:

NSMutableArray *array = [[NSMutableArray alloc] init];
NSArray * values = [dictionary allValues];
[array addObject:values];

Fragmento de código 2: Si desea agregar más

[array addObject:value1];
[array addObject:value2];
[array addObject:value3];

Y así sucesivamente

También puede almacenar los valores clave del diccionario en array

NSArray *keys = [dictionary allKeys];
 3
Author: Yogeesh H T,
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
2015-11-20 06:31:35

Hay algunas cosas que podrían estar sucediendo aquí.

¿Es el diccionario que has enumerado el myDict? Si es así, entonces no tiene un objeto con una clave de @"items", y la variable dict será nil. Necesita iterar a través de myDict directamente.

Otra cosa a comprobar es si _myArray es una instancia válida de un NSMutableArray. Si es nil, el método addObject: fallará silenciosamente.

Y una última cosa a comprobar es que los objetos dentro de su diccionario están correctamente encapsulados en NSNumbers (o algún otro tipo no primitivo).

 2
Author: Matt B.,
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
2010-02-16 16:02:58

Solo necesita inicializar su NSMutableArray

NSMutableArray  *myArray = [[NSMutableArray alloc] init];
 1
Author: AP Singh,
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
2015-04-24 05:36:50

Este código se usa realmente para agregar valores a dictionary y through los datos a un Array De acuerdo con el Key.

NSMutableArray *arr = [[NSMutableArray alloc]init];
NSDictionary *dicto = [[NSMutableDictionary alloc]initWithObjectsAndKeys:@"Hello",@"StackOverFlow",@"Key1",@"StackExchange",@"Key2", nil];
NSLog(@"The dictonary is = %@", dicto);
arr = [dicto valueForKey:@"Key1"];
NSLog(@"The array is = %@", arr);
 1
Author: onCompletion,
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
2016-08-09 06:49:55
+ (NSArray *)getArrayListFromDictionary:(NSDictionary *)dictMain paramName:(NSString *)paramName
{
    if([dictMain isKindOfClass:[NSDictionary class]])
    {
        if ([dictMain objectForKey:paramName])
        {
            if ([[dictMain objectForKey:paramName] isKindOfClass:[NSArray class]])
            {
                NSArray *dataArray = [dictMain objectForKey:paramName];

                return dataArray;
            }
        }
    }
    return [[NSArray alloc] init];
}

Espero que esto ayude!

 1
Author: Dharmesh Mansata,
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
2018-05-08 07:45:14

Para obtener todos los objetos en un diccionario, también puede usar enumerateKeysAndObjectsUsingBlock: así:

NSMutableArray *yourArray = [NSMutableArray arrayWithCapacity:6];
[yourDict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
    [yourArray addObject:obj];
}];
 0
Author: pixelfreak,
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
2011-12-09 02:06:34

En Swift 4:

let dict = ["Item1":2.4, "Item2": 5.4, "Item3" : 6.5]

let array = Array(dict.values)
 0
Author: Ankit garg,
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
2017-10-13 07:04:18