Ios 按word搜索核心数据

Ios 按word搜索核心数据,ios,iphone,objective-c,core-data,nspredicate,Ios,Iphone,Objective C,Core Data,Nspredicate,我有一个核心数据对象Contact Contact ======= fullName 我正在使用NSFetchedResultsController显示联系人列表 我现在想添加如下行为的搜索选项: 如果用户搜索字符串“da”,结果应为: 亚伦·大卫 伯特·丹尼尔斯 达纳 约翰·大卫 因此,搜索结果是按字母排序的字符串,该字符串有一个以“da开头的单词 我记得看过一个WWDC会话,演示了如何创建一个Word对象并独立存储每个单词,但我试图避免这种方法 所以我的问题是,我可以用我当前的模型结构和一

我有一个核心数据对象
Contact

Contact
=======
fullName
我正在使用
NSFetchedResultsController
显示联系人列表

我现在想添加如下行为的搜索选项:

如果用户搜索字符串“da”,结果应为:

亚伦·大卫
伯特·丹尼尔斯
达纳
约翰·大卫

因此,搜索结果是按字母排序的字符串,该字符串有一个以“da开头的单词

我记得看过一个WWDC会话,演示了如何创建一个Word对象并独立存储每个单词,但我试图避免这种方法

所以我的问题是,我可以用我当前的模型结构和一些谓词魔法来进行这样的搜索,还是必须将全名存储为单独的单词?

我就是这么做的:

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

您需要对数组中按名称筛选的单词使用谓词。使用方法如下:-

//Assuming you have store the name in one array
NSArray *names=@[@"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 yourStringValue=@"on"
NSPredicate *pd=[NSPredicate predicateWithFormat:@"self CONTAINS[CD] %@",yourStringValue];

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

"Aaron David"

什么是过滤器预测?它是我的通用主过滤器。在我的例子中:NSPredicate*filterPredicate=[NSPredicate predicateWithFormat:@“deletedServer==%@,[NSNumber numberWithBool:NO]];你不必使用它,只需要做一个空谓词。但是你把搜索字符串分解成单词,我不需要这样做,我需要按单词查找结果。我确信这不是OP的想法。由于缺少更好的示例,解决方案应该返回“Oneida Smith”或“King Ontario”。但肯定不是亚伦大卫。