can NSPredicates be used to replace objects in an array with values from a dictionary?

363 views Asked by At

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?

1

There are 1 answers

3
Nick Lockwood On BEST ANSWER

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.