【问题标题】:Core Data search by word核心数据按词搜索
【发布时间】:2014-05-06 03:41:02
【问题描述】:

我有一个核心数据对象Contact

Contact
=======
fullName

我正在使用NSFetchedResultsController 来显示联系人列表。

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

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

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

所以搜索结果是按字母排序的字符串,其中有一个单词以“da”开头

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

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

【问题讨论】:

    标签: ios iphone objective-c core-data nspredicate


    【解决方案1】:

    您需要对数组中按名称过滤的单词使用谓词。在下面使用:-

    //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"
    

    【讨论】:

    • 我确信这不是 OP 的想法。由于缺少更好的示例,该解决方案应该返回“Oneida Smith”或“King Ontario”。但肯定不是亚伦大卫。
    【解决方案2】:

    这就是我的工作:

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

    【讨论】:

    • 什么是filterPredicate?
    • 这是我的通用主过滤器。就我而言: NSPredicate *filterPredicate = [NSPredicate predicateWithFormat:@"deletedServer == %@",[NSNumber numberWithBool:NO]];您不必使用它,只需创建一个空谓词即可。
    • 但是你将搜索字符串分解为单词,我不需要这样做我需要按单词查找结果
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多