使用 NSPredicate 在单个搜索 iOS swift 中搜索多个单词

Posted

技术标签:

【中文标题】使用 NSPredicate 在单个搜索 iOS swift 中搜索多个单词【英文标题】:Search multi words in a single search iOS swift using NSPredicate 【发布时间】:2017-03-28 04:30:25 【问题描述】:

我想通过从详细列表中输入多个单词来搜索列表。 例如, 在索赔请求列表中,有不同类型的标签,例如金额、请求者姓名、请求名称和编号。所以我想从这个标签中搜索任何东西,这样我就可以找到确切的请求。

【问题讨论】:

向我们展示您的尝试? 使用filterNSPredicate 更容易 其实我已经关注了:(theappguruz.com/blog/tableview-search-in-swift) 这个单搜索。但找不到多字。 如何编写 nspredicate 的语法以在搜索栏中搜索以下这些 requestTypeArr = [] requestorEmployeeArr = [] regNoArr = [] amountOrDaysArr = [] 你使用 5 个数组作为单元格标签? 【参考方案1】:
var predicateList = [NSPredicate]()

let words = filterText.componentsSeparatedByString(" ")

for word in words

 if count(word)==0
       continue
 

 let RequestTypeArray = NSPredicate(format: "RequestType contains[c] %@", word)
 let RequestEmployeeArray = NSPredicate(format: "RequestorEmployee contains[c] %@", word)
 let RegesterNumberArray = NSPredicate(format: "ReqNo contains[c] %@", word)
 let AmountOrDaysArray = NSPredicate(format: "AmountOrDays contains[c] %@", word)

 let orCompoundPredicate = NSCompoundPredicate(type: NSCompoundPredicateType.OrPredicateType, subpredicates: [firstNamePredicate, lastNamePredicate,departmentPredicate,jobTitlePredicate])

 predicateList.append(orCompoundPredicate)


  request.predicate = NSCompoundPredicate(type:    NSCompoundPredicateType.AndPredicateType, subpredicates: predicateList)

【讨论】:

当我写上面的代码时 let words = filterText.componentsSeparatedByString(" ") for word in words if count(word)==0 continue 我得到一个错误 ::: Use of unresolved identifier “过滤文本” func filterTableViewForEnterText(searchText: String) // 此 searchText 用作 filterText 让 words = filterText.componentsSeparatedByString(" ") 我得到类型为 '(String) -> ()' 的错误值没有成员 'componentsSeparatedByString'【参考方案2】:

也许这个答案对你有帮助..

let addresspredicate = NSPredicate(format: "address_name contains[c] %@",searchText)
    let accnopredicate = NSPredicate(format: "acc_no contains[c] %@",searchText)
    let propertytype = NSPredicate(format: "property_type contains[c] %@",searchText)
    let subpropertytypoe = NSPredicate(format: "subproperty_type contains[c] %@",searchText)

    let predicateCompound = NSCompoundPredicate.init(type: .or, subpredicates: [addresspredicate,accnopredicate,propertytype,subpropertytypoe])
    filteredProperty = (propertyArray as Array).filter  predicateCompound.evaluate(with: $0) ;
    print("filteredProperty = ,\(filteredProperty)")

【讨论】:

以上是关于使用 NSPredicate 在单个搜索 iOS swift 中搜索多个单词的主要内容,如果未能解决你的问题,请参考以下文章

我如何在单个提取请求中调用两个 NSPredicate。核心数据 iOS Swift

使用 NSPredicate 搜索 NSArray

是否可以在 NSPredicate 中使用嵌套的 SUBQUERY?

使用 NSPredicate 和数组进行 cloudKit 搜索

使用 NSPredicate 搜索 NSFetchedResultsController

使用 NSPredicate 进行核心数据实体搜索