核心数据项目中的搜索栏

Posted

技术标签:

【中文标题】核心数据项目中的搜索栏【英文标题】:Search bar in core data project 【发布时间】:2013-07-01 09:28:55 【问题描述】:

我使用带有神奇记录的核心数据,并尝试在表格视图中使用搜索栏过滤数据。

我写了两种获取行数和单元格名称的方法:

    -(int) dammiNumeroCercati:(NSString *)searchBar

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"nome CONTAINS [cd] %@", searchBar];

    NSArray*arra = [Ricetta MR_findAllSortedBy:@"nome" ascending:YES withPredicate:predicate];


    return arra.count;

-(NSString*) dammiNomeRicettaCercata:(NSString *)searchBar mostrataNellaCella: (int) cella


   NSPredicate *predicate = [NSPredicate predicateWithFormat:@"nome CONTAINS [cd] %@", searchBar];

    NSArray *arra = [Ricetta MR_findAllSortedBy:@"nome" ascending:YES withPredicate:predicate];
    Ricetta*ctn = arra[cella];

    return [NSString stringWithFormat:@"%@", ctn.nome];

然后我在 numberOfRowsInSection: 和 cellForRowAtIndexPath: 中调用此方法:在 if 循环中:

if (self.mySearchBar.isFirstResponder)

// the above methods

 else 
 // the normals methods to have all the data

有人知道我错在哪里或者我错过了什么吗?

【问题讨论】:

有什么问题?你是如何调用上述方法的?比如你传递了什么参数? 即使有效:一次又一次地调用MR_findAllSortedBy 是非常无效的。你应该看看 NSFetchedResultsController。 @govi 问题是搜索栏不起作用 【参考方案1】:

searchBar 通常是UISearchBar,而不是字符串。

您应该使用searchBar.text 并在您的方法中处理它。

此外,在表格视图的数据源方法中,您必须确定哪个表格视图导致了回调,然后返回正确的计数/字符串。通常这是通过比较指向两个表(原始表视图和搜索结果表视图)的指针来检查的。

-(NSUInteger)tableView:(UITableView*)tableView 
       numberOfRowsInSection:(NSUInteger)section 

   if (tableView == _tableView) 
      // return the usual row count
   
   return [self dammiNumeroCercati:_searchBar.text];

【讨论】:

以上是关于核心数据项目中的搜索栏的主要内容,如果未能解决你的问题,请参考以下文章