1

If I had an NSDictionary like this:

NSMutableDictionary *valuesDictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithDouble:-60.0],@”a”,
[NSNumber numberWithDouble:0.0],@”b”,
[NSNumber numberWithDouble:-12.0],@”c”,
[NSNumber numberWithDouble:.3],@”x”, nil];

and an array like this:

NSArray *program = [NSArray arrayWithObjects: @"a",@"12.6",@"100",@"+",@"x",nil];

what would the code look like to return an array programWithVariableValues, for example, consisting of @”-60″,@”12.6″,@”100″,@"+",@”.3″,nil?

(replacing any variables found in the array with their valueforkey’s)

Would that be a good place to utilize NSPredicate? or just fast enumeration? or something else?

Dave Kliman
  • 441
  • 4
  • 17

1 Answers1

1

There may be a clever one-liner solution using predicates and/or valueForKeyPath operators, but until somebody figures that one out, this should do the trick:

NSMutableArray *programWithVariableValues = [NSMutableArray array];
for (NSString *key in program)
{
    [programWithVariableValues addObject:[[valuesDictionary objectForKey:key] description] ?: key];
}

The programWithVariableValues array now contains your values (as strings). If you'd prefer to keep the numbers as NSNumbers, take out the "[... description]" call.

Nick Lockwood
  • 40,865
  • 11
  • 112
  • 103
  • Thank you. that works great. so basically, if there isn't a match in the values dictionary, the ?: just puts the key in.. elegant. objc is growing on me. – Dave Kliman Jan 14 '12 at 03:44
  • Yes, "foo ?: bar" is basically a shorthand way of writing "foo ? foo: bar", or "if (foo) {return foo} else {return bar}". So the logic says "grab the object in the dictionary with key, and if that returns nil, just use the key instead" – Nick Lockwood Jan 14 '12 at 09:39
  • I have to get used to how most anything can become a conditional like that...it's pretty cool i think – Dave Kliman Jan 14 '12 at 16:31