6

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...

3 Answers 3

12

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];
Sign up to request clarification or add additional context in comments.

Comments

5

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];

Comments

2

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"];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.