0

I have to sort/search an array of dictionaries based on an array of tag ids.

The web service send a list of articles which have tag ids like [1,2,3,5] for every article.

The user selects multiple tags from a list and there tag ids are stored in an array like [4,2,8,1]

** Now i have to compare the user selected tags with the article tags and if any tag in the 2 arrays match it is stored in a result array **

What should I use and How? NSPredicate or a NSSortdescriptor

In short i have to do something like this:

userTags = [4,6,2,1]
articleTags = [1,2,3,4,5]

if ANY [userTags] IN [articleTags] 
  [resultArr addObject:article]

2 Answers2

1

I believe you should use NSSet for your task instead of NSArrays. And check if sets intersect, e.g.:

NSSet *tags = [NSSet setWithArray:@[@1, @3, @5]];

NSSet *article1 = [NSSet setWithArray:@[@2, @4, @6]];
NSSet *article2 = [NSSet setWithArray:@[@2, @3, @4]];
NSLog(@"%d", [tags intersectsSet:article1]);
// 0
NSLog(@"%d", [tags intersectsSet:article2]);
// 1
Mindaugas
  • 1,707
  • 13
  • 20
0

Mindaugas answer worked.

NSSet *selectedTagSet = [NSSet setWithArray:selectedTagIds];
NSMutableArray *result = [NSMutableArray array];

for (int i = 0; i < [self.responceArray count]; i++) {

    NSMutableDictionary *dict = [self.responceArray objectAtIndex:i];

    NSSet *tagSet = [NSSet setWithArray:[[dict objectForKey:@"seller"] objectForKey:@"tags"]];

    if ([tagSet intersectsSet:selectedTagSet])
    {
        [result addObject:[self.responceArray objectAtIndex:i]];
    }

}