2014-11-06 27 views
1

我想構建一個核心數據存儲的查詢,該查詢在長字符串中出現時檢索實體的屬性值;編寫'CONTAINED_BY'文本查詢的NSPredicate

即,而不是尋求例子,其中屬性值包含一個(短)字符串:

request.predicate = [NSPredicate predicateWithFormat:@"carBrand contains[c] 'merced'"] 

我想找到(的實體),其屬性值被發現情況下,「包含在」任意(更長)字符串:

NSString* textString = @"Elaine used to drive Audis, but now owns a Mercedes"; 
request.predicate = [NSPredicate predicateWithFormat:@"%@ contains[c] carBrand", textString ]; 

(即檢索陣列保持與carBrand = @ 「奧迪」 和carBran對象。 d = @「奔馳」)

在我的嘗試,NSPredicate似乎並不喜歡在右側的屬性名稱表達並拋出一個錯誤...

[__NSCFConstantString countByEnumeratingWithState:對象:數:]:無法識別 選擇發送到實例0X

...有在左手側的屬性名構建這樣一個查詢的方式 - 一個「contained_by」查詢,因爲它是?

PS。搜索SO,我只發現solutions by splitting the text into component words,在我的情況下,將不理想!這是唯一可行的方法嗎?

回答

1

用您的數組構建正則表達式字符串,並在謂詞中使用MATCHES

​​3210

要根據自己的品牌篩選汽車:

NSArray *brands = [@"Audi", @"Mercedes"]; 
[NSPrediate predicateWithFormat:@"carBrand IN %@", brands]; 
+0

在我的例子中,我希望找到*我的db中的許多Cars中的哪一個具有匹配字符串的某個部分的.carBrand。你的問題不能確認奧迪|梅賽德斯是否在線中? – cate 2014-11-06 12:15:51

+0

是的,這個例子只是返回包含奧迪或奔馳的原始字符串,而沒有改變它們。 – 2014-11-06 12:18:19

+0

編輯以澄清所需結果的問題是實體*的*數組,其給定*屬性值*與任意動態搜索源字符串的某個子字符串匹配。 – cate 2014-11-06 13:49:24

0

決定嘗試實施componentsSeparatedByString的方法來建立一個NSCompoundPredicate

//find alphabetic words omitting standard plurals 
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(?:[^a-z]*)([a-z]+?)(?:s)?\\W+" options:NSRegularExpressionCaseInsensitive error:nil]; 

//separate with pipe| and split into array 
NSString *split = [regex stringByReplacingMatchesInString:textString options:0 range:NSMakeRange(0, speciesString.length) withTemplate:@"$1|"]; 
NSArray *words = [split componentsSeparatedByString:@"|"]; 

//build predicate List 

NSMutableArray *predicateList = [NSMutableArray array]; 
for (NSString *word in words) { 
    if ([word length] > 2) { 
     NSPredicate *pred = [NSPredicate predicateWithFormat:@"brandName beginswith[c] %@", word]; 
     [predicateList addObject:pred]; 
    } 
} 
//CarBrand* object; 
NSFetchRequest *request = [[NSFetchRequest alloc] init]; 
request.entity = [NSEntityDescription entityForName:@"CarBrand" inManagedObjectContext:self.managedObjectContext]; 
request.predicate = [NSCompoundPredicate orPredicateWithSubpredicates:predicateList]; 

NSError *error =nil; 
NSArray *results = [self.managedObjectContext executeFetchRequest:request error:&error]; 

這檢索的文本中發現的情況; eg1:

@「伊萊恩曾經駕駛奧迪斯,但現在擁有一輛梅賽德斯」;

分別給出了.brandname =「Audi」,「Mercedes」的對象數組。

EG2:@ 「在被盜汽車是福特蒙迪歐,一個菲亞特500C和 阿爾法羅密歐Spyder的」

產量.brandname = 「福特」, 「菲亞特」 和「阿爾法羅密歐「(NB no' - ')。

我還沒有接受我自己的答案,因爲它似乎太多的解決方法,不會輕易擴展到(例如)提取品牌名稱和模型。

希望有人會有更好的解決方案!