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;
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 :)
What about this?
NSString *value = [dictionary valueForKey:@"myKey"];
if (!value) value = @"defaultValue";
[myObject setMyString:value];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With