2017-03-06 51 views
0

有一個名爲"keyword"的實體,其中包含逗號分隔值,如"8275,8276,8277"。現在使用NSPredicate搜索那些關鍵字與此匹配並且傳遞值爲NSArray的用戶。嘗試使用(keywords contains[cd] %@)獲取單個值,但不能用於數組。NSPredicate搜索逗號分隔值與數組

謂詞就是這樣,

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

打印謂語之後,它就像 -

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

嘗試複合謂語也喜歡

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

也沒有工作。任何想法,我做錯了。

+0

入住這http://stackoverflow.com/questions/37919934/nspredicate-for-exact-match – kb920

+0

檢查了這一點,但無法得到它如何爲「fetchRequest」的工作邏輯 –

+0

@SantanuDasAdhikary檢查我回答一次。 –

回答

0

您需要從您的predicate中刪除keywords contains[cd] %@,然後CompoundPredicate適合您。

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

謝謝,工作正常:) –

+0

@SantanuDasAdhikary歡迎伴侶:) –