问题
(My english is not good).
I have two NSArray.
EXAMPLE: 1st NSArray is storing
NSArray category= { ID:1,Name:Category1;ID:2, Name: Category2;ID:3, Name:Category3;}
2nd NSArray is storing
NSArray product= {cat_ID:1, Category-Name:Category1, product_ID:1, Name: Banana;
cat_ID:1, Category-Name:Category1, product_ID:2, Name: apple;
cat_ID:1, Category-Name:Category1, product_ID:3, Name: berry;
cat_ID:2, Category-Name:Category2, product_ID:4, Name: cantaloupe;
cat_ID:2, Category-Name:Category2, product_ID:5, Name: elderberry;
cat_ID:2, Category-Name:Category2, product_ID:6, Name: ginger;
cat_ID:2, Category-Name:Category2, product_ID:7, Name: watermelon;
cat_ID:3, Category-Name:Category3, product_ID:8, Name: xigua;
cat_ID:3, Category-Name:Category3, product_ID:9, Name: avocado;
cat_ID:3, Category-Name:Category3, product_ID:10, Name: basil;
cat_ID:3, Category-Name:Category3, product_ID:11, Name: alfalfa;
cat_ID:3, Category-Name:Category3, product_ID:12, Name: blackcurrant;}
All i want is if category name (i mean 1st NSArray category.name) is equals to 2nd NSArray's category name (i mean product.Category-Name) then print all product name. Example: category.name== Category1; then result will be Product.Name = Banana, Apple, Berry;
How to do this?
回答1:
From your json-like notation, we will assume that key value pairs in "{...}" are NSDictionary objects. And you have an array of said NSDictionary objects, "[{...},{...},...]"
To get the products for a given category:
NSString *category = @"Category1";
NSArray *result = [NSArray array];
for (NSDictionary *dic in products) {
if ([[dic objectForKey:@"Category-Name"] isEqualToString: category])
result = [result arrayByAddingObject: [dic objectForKey: @"Name"] ];
}
回答2:
I would suggest you not to make Array for this kind of logic.
You should use NSDictionary/NSMutableDictionary.
Then you can filter easily by NSPredicateFilter.
回答3:
You can also do this task in compact way by using NSPredicate
NSString *selectedCategory = @"Category1";
//filter array by category using predicate
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"Category-Name == %@", selectedCategory];
NSArray *filteredArray = [product filteredArrayUsingPredicate:predicate];
or just follow my blog rajneesh071.blogspot.in for more info
来源:https://stackoverflow.com/questions/13717735/showing-value-from-nsarray-on-the-basis-of-other-nsarray