Pregunta

Tengo que comprobar si un dict tiene una tecla o no. ¿Cómo?

¿Fue útil?

Solución

objectForKey devolverá nil si no existe una clave.

Otros consejos

if ([[dictionary allKeys] containsObject:key]) {
    // contains key
}

o

if ([dictionary objectForKey:key]) {
    // contains object
}

Las versiones más recientes de Objective-C y Sonido metálico tienen una sintaxis moderna para esto:

if (myDictionary[myKey]) {

}

Usted no tiene que comprobar la igualdad con el nula, ya que los objetos de Objective-C único no-nil se pueden almacenar en los diccionarios (o matrices). Y todos los objetos de Objective-C son valores Truthy. @NO Incluso, @0 y [NSNull null] evalúan como verdadero.

Editar: Swift es ahora una cosa.

Para Swift usted intentaría algo como lo siguiente

if let value = myDictionary[myKey] {

}

Esta sintaxis sólo se ejecutará si el bloque si es myKey en el dict y si es entonces el valor se almacena en la variable de valor. Tenga en cuenta que esto funciona para valores Falsey incluso como 0.

if ([mydict objectForKey:@"mykey"]) {
    // key exists.
}
else
{
    // ...
}

Cuando se utiliza JSON diccionarios:

#define isNull(value) value == nil || [value isKindOfClass:[NSNull class]]

if( isNull( dict[@"my_key"] ) )
{
    // do stuff
}

I como respuesta Fernandes' a pesar de que solicite la obj dos veces.

Esto también debería hacer (más o menos lo mismo que una de Martin).

id obj;

if ((obj=[dict objectForKey:@"blah"])) {
   // use obj
} else {
   // Do something else like creating the obj and add the kv pair to the dict
}

Martin y de esta respuesta, tanto en el trabajo iPad2 iOS 5.0.1 9A405

Uno de gotcha muy desagradable, que acaba de perder un poco de mi tiempo de depuración -. Usted puede encontrarse motivada por la función de autocompletar intentar usar doesContain que parece funcionar

A excepción, doesContain utiliza una comparación de ID en lugar de la comparación de hash utilizado por objectForKey por lo que si usted tiene un diccionario con claves de cadena que no devolverá a un doesContain.

NSMutableDictionary* keysByName = [[NSMutableDictionary alloc] init];
keysByName[@"fred"] = @1;
NSString* test = @"fred";

if ([keysByName objectForKey:test] != nil)
    NSLog(@"\nit works for key lookups");  // OK
else
    NSLog(@"\nsod it");

if (keysByName[test] != nil)
    NSLog(@"\nit works for key lookups using indexed syntax");  // OK
else
    NSLog(@"\nsod it");

if ([keysByName doesContain:@"fred"])
    NSLog(@"\n doesContain works literally");
else
    NSLog(@"\nsod it");  // this one fails because of id comparison used by doesContain

El uso de Swift, sería:

if myDic[KEY] != nil {
    // key exists
}

Sí. Este tipo de errores son muy comunes y dar lugar a accidente aplicación. Así que utilizo para agregar NSDictionary en cada proyecto de la siguiente manera:

// h código del archivo:.

@interface NSDictionary (AppDictionary)

- (id)objectForKeyNotNull : (id)key;

@end

//. M Código de archivos es la siguiente

#import "NSDictionary+WKDictionary.h"

@implementation NSDictionary (WKDictionary)

 - (id)objectForKeyNotNull:(id)key {

    id object = [self objectForKey:key];
    if (object == [NSNull null])
     return nil;

    return object;
 }

@end

En el código se puede utilizar de la siguiente manera:

NSStrting *testString = [dict objectForKeyNotNull:@"blah"];

Para la comprobación de la existencia de la clave en NSDictionary:

if([dictionary objectForKey:@"Replace your key here"] != nil)
    NSLog(@"Key Exists");
else
    NSLog(@"Key not Exists");

Debido a cero no se puede almacenar en la Fundación estructuras de datos NSNull es a veces para representar un nil. Debido NSNull es un objeto único se puede comprobar para ver si NSNull es el valor almacenado en el diccionario utilizando comparaciones puntero directo:

if ((NSNull *)[user objectForKey:@"myKey"] == [NSNull null]) { }

Solution for swift 4.2

So, if you just want to answer the question whether the dictionary contains the key, ask:

let keyExists = dict[key] != nil

If you want the value and you know the dictionary contains the key, say:

let val = dict[key]!

But if, as usually happens, you don't know it contains the key - you want to fetch it and use it, but only if it exists - then use something like if let:

if let val = dict[key] {
    // now val is not nil and the Optional has been unwrapped, so use it
}

I'd suggest you store the result of the lookup in a temp variable, test if the temp variable is nil and then use it. That way you don't look the same object up twice:

id obj = [dict objectForKey:@"blah"];

if (obj) {
   // use obj
} else {
   // Do something else
}

As Adirael suggested objectForKey to check key existance but When you call objectForKeyin nullable dictionary, app gets crashed so I fixed this from following way.

- (instancetype)initWithDictionary:(NSDictionary*)dictionary {
id object = dictionary;

if (dictionary && (object != [NSNull null])) {
    self.name = [dictionary objectForKey:@"name"];
    self.age = [dictionary objectForKey:@"age"];
}
return self;

}

if ([MyDictionary objectForKey:MyKey]) {
      // "Key Exist"
} 
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top