【问题标题】:Optimize Search Result from address book in iphone优化 iphone 通讯录中的搜索结果
【发布时间】:2012-03-19 16:36:44
【问题描述】:

当用户搜索时,我想根据地址簿数据搜索该查询,以获取姓名、电话号码、网址、电子邮件地址等任何内容。我的解决方案运行良好,但速度很慢。如果通讯录数据很大,应用就会卡住。如何优化搜索,让我的应用程序即使在通讯录数据很大时也不会挂起?

这是我的代码

 - (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    [self takeSomeActionWhenTextChange];  
}

-(void)takeSomeActionWhenTextChange{
    [contactArray removeAllObjects];
    NSString *searchText=[[textSearchBar text] lowercaseString];


    for (int index=0; index<count; index++) {
        ABRecordRef record=CFArrayGetValueAtIndex(people, index);
        //[self checkStringISAddress:searchText withRecord:record];
        if ([self checkStringIsFirstName:searchText withRecord:record]==YES 
        || [self checkStringIsLastName:searchText withRecord:record] == YES
        ||[self checkStringIsNote:searchText withRecord:record]==YES 
        || [self checkStringIsAddress:searchText withRecord:record]==YES 
        || [self checkStringIsCompany:searchText withRecord:record]==YES 
        ||[self checkStringIsEmail:searchText withRecord:record]
        ||[self checkStringIsPhonenumber:searchText withRecord:record]==YES )
        {
            NSLog(@"object added inside Array");
            [contactArray addObject:record];
            [contactTableView reloadData];
        }else{
            NSLog(@"No Match For this object");
            [contactTableView reloadData];

        }

    }

}

我将检查搜索查询中的子字符串是否与名字、姓氏、电子邮件等匹配。上述方法包含检查子字符串是否存在的逻辑?如果 ti 匹配,我会将其添加到数组中,否则不添加。

我应该使用线程还是 GCD 来执行搜索?如果是,如何?如何更新我的表格视图?

【问题讨论】:

    标签: iphone objective-c addressbook


    【解决方案1】:

    您可以使用 GCD,但仍应显示活动指示器以向用户显示正在发生的事情。它只会防止主线程阻塞,以及 UI 锁定。

    未测试,当然你也可以使用不同的常量来设置队列的优先级:

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    
        //Perform the search
        //perform your search here...
    
        dispatch_async(dispatch_get_main_queue(), ^{
    
            //Update the UI
            [self.tableView reloadData];
        });
    });
    

    您可能还想看看使用谓词而不是只检查子字符串,这可能会给您一些更清晰的逻辑。

    【讨论】:

    • 感谢您的回复。所以你的意思是我应该使用 NSPredciate 而不是手动检查?如果是,你能告诉我如何使用谓词吗?
    • 在 SO 中搜索“NSPredicate”应该会给你很多例子。文档在这里:developer.apple.com/library/ios/#documentation/Cocoa/Reference/…
    • 感谢您的链接。我看到了这个文档。但我的问题是如何使用谓词来搜索我的查询对所有属性,如名字、姓氏、地址、便笺、电子邮件、ph 号等?我应该对每个属性使用一个谓词还是有其他方法?因为我必须搜索上面提到的所有属性。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多