gpt4 book ai didi

swift - 具有核心数据问题的搜索栏

转载 作者:行者123 更新时间:2023-11-28 10:24:31 26 4
gpt4 key购买 nike

我有一个搜索栏。数据显示在带有 ScrollView 的标签中。

例如:

核心数据字段:

1.id
2.公司
3.员工姓名

4.地址

如果我在搜索栏中输入 id、公司或员工姓名,我想显示相关结果。

我的代码:

对于搜索数据:

  func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {

var request = NSFetchRequest(entityName: "Agency")
request.returnsObjectsAsFaults = false
var countResult : NSArray = context.executeFetchRequest(request, error: nil)!



let result = NSPredicate(format: "SELF CONTAINS[c] %@",searchText)


self.filtered = self.countResult.filteredArrayUsingPredicate(result!)



if (filtered.count == 0 ) {
searchActive = false;
}else {
searchActive = true;
}

println(filtered)

}

它显示错误“'不能在集合中使用/包含运算符”。

这些代码无法满足我的需求。而且我也不知道如何根据搜索栏中的输入值获取相关行。

提前致谢。

最佳答案

第一个问题是您的谓词 - 您试图在 NSManagedObject 子类上使用 CONTAINS,但 CONTAINS 仅适用于 字符串。要检查您的搜索文本是否包含在您的任何托管对象中,您需要评估它是否包含在每个属性中(在您的情况下为 idcompany empolyeeName,我假设它们都是 String)。

为此,您应该将谓词更改为:

let searchPredicate = NSPredicate(format: "id BEGINSWITH %@ OR
company BEGINSWITH %@ OR
employeeName BEGINSWITH %@",
searchText, searchText, searchText)

我建议使用 BEGINSWITH 而不是 CONTAINS[c],因为在搜索时您的用户很可能会输入短语的第一部分。此外,正如 Apple 在其 2013 年 WWDC 演讲中所说,核心数据性能优化和调试 -

...we've got begins with and ends with and that's by far the cheapest query that you can execute.

...

Contains is more expensive because we have to work along and see whether it contains...

在搜索的情况下,您希望搜索速度快!

其次,您不需要在从 CoreData 取回结果后对其进行过滤。您可以在 NSFetchRequest 上设置 predicate 属性,您返回的结果将被过滤。例如:

let request = NSFetchRequest(entityName: "Agency")
request.predicate = // Your predicate...

let results = context.executeFetchRequest(request, error)
// Now do what you need with the results.

最后一点,最好不要强制从 executeRequest 解包结果,以防出现问题并返回 nil - 在这种情况下,您的应用程序会崩溃。您可以改为使用:

if let unwrappedResults = results {
// Now do what you want with the unwrapped results.
}

关于swift - 具有核心数据问题的搜索栏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29534089/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com