2014-03-27 33 views
1

核心數據搜索我有一個核心數據對象Contact通過字

Contact 
======= 
fullName 

我使用的是NSFetchedResultsController顯示的聯繫人列表。

現在我想補充一點,表現爲如下的搜索選項:

如果字符串「DA」用戶搜索,結果應該是:

亞倫大衛
貝爾·丹尼爾斯
達納
John David

所以搜索結果是字母排序字符串具有開始「DA

我記得看演示如何創建一個Word對象和獨立存儲每個字WWDC會議,但我試圖避免使用此方法。

所以我的問題是,我可以用我目前的模型結構和一些謂詞魔術做這樣的搜索,或者我必須將fullName作爲單獨的詞存儲?

回答

0

這是我做的:

NSMutableArray *predicateArray = [NSMutableArray array]; 
if(searchString.length) 
{ 
    for (NSString* searchStringPart in [searchString componentsSeparatedByString:@" "]) 
    { 
     if([searchStringPart length] > 0) 
     { 
      [predicateArray addObject:[NSPredicate predicateWithFormat:@"name CONTAINS[cd] %@", searchStringPart]]; 
     } 
    } 

    filterPredicate = [NSCompoundPredicate andPredicateWithSubpredicates:@[filterPredicate, [NSCompoundPredicate andPredicateWithSubpredicates:predicateArray]]]; 
} 

而對於排序:

NSSortDescriptor *sort = [[[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES] autorelease]; 
NSArray* sortDescriptors = @[sort]; 
.... 
[fetchRequest setSortDescriptors:sortDescriptors]; 
+0

什麼是filterPredicate? – Eyal

+0

它是我的一般主濾鏡。在我的情況:NSPredicate * filterPredicate = [NSPredicate predicateWithFormat:@「deletedServer ==%@」,[NSNumber numberWithBool:NO]];您不必使用它,只需創建一個空謂詞。 –

+0

但你打破搜索字符串的話,我不需要做它我需要找到結果的話 – Eyal

0

您需要通過名稱陣列中使用謂詞過濾詞。以下用途: -

//Assuming you have store the name in one array 
NSArray *[email protected][@"Aaron David",@"Bert Daniels",@"Dana",@"John David"];  

//Now use contains in predicate for filtered words 
//On the basis of search string it will filtered accordingly. lets Say [email protected]"on" 
NSPredicate *pd=[NSPredicate predicateWithFormat:@"self CONTAINS[CD] %@",yourStringValue]; 

NSArray *ar=[names filteredArrayUsingPredicate:pd]; 
NSLog(@"%@",ar); 

輸出: -

"Aaron David"