Retrieving strings from NSArray objects based on an NSStrings array

Well, this is a little obscure, but it gives me a headache.

If you have an array of strings

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

And you have an 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 I, using the first array, create such an array:

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

In his words, he takes the numbers in the first array and creates an array recipe_names, where recipe_id matches the numbers ...

+7
ios objective-c iphone nsarray
source share
3 answers

Use NSPredicate to specify the type of objects you want, then use -[NSArray filteredArrayUsingPredicate:] to select exactly 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 create 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]; 
+12
source share

Your array of recipe objects is basically a dictionary:

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

And in the dictionary you can use the encoding method by key value:

 NSArray *result = [[recipeDict dictionaryWithValuesForKeys:recipeIDs] allValues]; 
+5
source share

Assuming your Recipe objects are compatible with key values ​​(they almost always exist), you can use the predicate like this:

 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"]; 
+2
source share

All Articles