Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting strings from a NSArray of objects, based on a array of NSStrings

OK, this is a bit obscure, but it's giving me a headache.

If you have an array of strings

{@"1", @"2", @"4"}

And you have a array of Recipe objects

{ {recipe_name:@"Lasagna", recipe_id:@"1"}
  {recipe_name:@"Burger", recipe_id:@"2"}
  {recipe_name:@"Pasta", recipe_id:@"3"}
  {recipe_name:@"Roast Chicken", recipe_id:@"4"}
  {recipe_name:@"Sauerkraut", recipe_id:@"5"}
}

How would I, using the first array, create an array like this:

{@"Lasagna", @"Burger", @"Roast Chicken"}

In ither words, it is taking the numbers in the first array and creating an array of recipe_names where the recipe_id matches the numbers...

like image 335
cannyboy Avatar asked Nov 17 '10 23:11

cannyboy


3 Answers

Use an NSPredicate to specify the type of objects you want, then use -[NSArray filteredArrayUsingPredicate:] to select precisely those objects:

NSArray *recipeArray = /* array of recipe objects keyed by "recipe_id" strings */;
NSArray *keyArray = /* array of string "recipe_id" keys */;
NSPredicate *pred = [NSPredicate predicateWithFormat:@"recipe_id IN %@", keyArray];
NSArray *results = [recipeArray filteredArrayUsingPredicate:pred];

NSPredicate uses its own mini-language to build a predicate from a format. The format grammar is documented in the "Predicate Programming Guide."

If you are targeting iOS 4.0+, a more flexible alternative is to use -[NSArray indexesOfObjectsPassingTest:]:

NSIndexSet *indexes = [recipeArray indexesOfObjectsPassingTest:
        ^BOOL (id el, NSUInteger i, BOOL *stop) {
            NSString *recipeID = [(Recipe *)el recipe_id];
            return [keyArray containsObject:recipeID];
        }];
NSArray *results = [recipeArray objectsAtIndexes:indexes];
like image 171
Jeremy W. Sherman Avatar answered Nov 09 '22 19:11

Jeremy W. Sherman


Your array of recipe objects is basically a dictionary:

NSDictionary *recipeDict =
  [NSDictionary dictionaryWithObjects:[recipes valueForKey:@"recipe_name"]
                              forKeys:[recipes valueForKey:@"recipe_id"]];

And on a dictionary you can use the Key-Value Coding method:

NSArray *result = [[recipeDict dictionaryWithValuesForKeys:recipeIDs] allValues];
like image 36
w-m Avatar answered Nov 09 '22 19:11

w-m


Assuming that your Recipe objects are key-value compliant (which they almost always are) you can use a predicate like so:

NSArray *recipes= // array of Recipe objects
NSArray *recipeIDs=[NSArray arrayWithObjects:@"1",@"2",@"3",nil];
NSPredicate *pred=[NSPredicate predicateWithFormat:@"recipe_id IN %@", recipeIDs];
NSArray *filterdRecipes=[recipes filteredArrayUsingPredicate:pred];
NSArray *recipeNames=[filterdRecipes valueForKey:@"recipe_name"];
like image 2
TechZen Avatar answered Nov 09 '22 19:11

TechZen