iosobjective-carraysnspredicatenscompoundpredicate

NSPredicate search comma separated value with array


Have a entity filed called "keyword" which containing comma separated value like "8275,8276,8277". Now using NSPredicate search those users whose keyword matching on this and the passing value is an NSArray. Trying to fetch using (keywords contains[cd] %@) which is working single value, not working for an array.

The predicate is like that,

[NSPredicate predicateWithFormat:@"((eventId == %@) AND (keywords contains[cd] %@) AND (attendeeIsVisible == %@))",self.appDelegate.currentEvent.entityId,selectedTagID,[NSNumber numberWithInt:1]]

After printing the predicate it's like -

eventId == 18230 AND keywords CONTAINS[cd] {"8275", "8276", "8277"} AND attendeeIsVisible == 1

Trying the compound Predicate also like

NSMutableArray *parr = [NSMutableArray array];
for (id locaArrayObject in selectedTagID) {
   [parr addObject:[NSPredicate predicateWithFormat:@"keywords contains[cd] %@ ",locaArrayObject]];
}

predicate = [NSPredicate predicateWithFormat:@"((eventId == %@) AND (keywords contains[cd] %@) AND (attendeeIsVisible == %@))",self.appDelegate.currentEvent.entityId,selectedTagID,[NSNumber numberWithInt:1]];

NSPredicate *predicateObj = [NSCompoundPredicate andPredicateWithSubpredicates:@[predicate, parr]];

Not working also. Any idea where I am doing wrong.


Solution

  • You need to remove keywords contains[cd] %@ from your predicate then CompoundPredicate works for you.

    NSMutableArray *parr = [NSMutableArray array];
    for (id locaArrayObject in selectedTagID) {
        [parr addObject:[NSPredicate predicateWithFormat:@"keywords contains[cd] %@ ",locaArrayObject]];
    }
    
    NSPredicate *eventPredicate = [NSPredicate predicateWithFormat:@"((eventId == %@) AND (attendeeIsVisible == %@))",self.appDelegate.currentEvent.entityId,[NSNumber numberWithInt:1]];
    
    NSPredicate *keywordPredicate = [NSCompoundPredicate orPredicateWithSubpredicates: parr];
    
    //Now use below predicate with your array
    predicate = [NSCompoundPredicate orPredicateWithSubpredicates: [eventPredicate, keywordPredicate]];