Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSString and NSDictionary valueForKey - nil?

How can I put a default value into my string if getting data from an empty key/value in a dictionary.

so [myObject setMyString:[dictionary valueForKey:@"myKey"]];

So then if I did NSString *newString = myObject.myString I would get an unrecognized selector error.

So again, I simply need a way to insert a default string if the key value is empty;

like image 296
spentak Avatar asked Oct 05 '11 16:10

spentak


2 Answers

If dictionary is a NSDictionary you should probably use objectForKey as valueForKey is used for KVC. It works for NSDictionary but may bite you if the key collide with some NSDictionary KVC key, e.g. "@allKeys" or "@count".

I think the shortest is probably to do:

[dictionary objectForkey:@"myKey"] ?: @"defaultValue"

There is one terrible way of abusing the existing dictionary methods to produce a get by key or return a default value if you don't want to use a condition for some reason...

[[dictionary objectsForKeys:[NSArray arrayWithObject:@"myKey"]
             notFoundMarker:@"defaultValue"]
 objectAtIndex:0]

You did not hear it from me :)

like image 132
Mattias Wadman Avatar answered Oct 06 '22 01:10

Mattias Wadman


What about this?

NSString *value = [dictionary valueForKey:@"myKey"];
if (!value) value = @"defaultValue";
[myObject setMyString:value];
like image 21
Nekto Avatar answered Oct 06 '22 01:10

Nekto