【问题标题】:How to add search in table view in NSMutableArray如何在 NSMutableArray 的表视图中添加搜索
【发布时间】:2016-12-10 21:17:13
【问题描述】:

我想使用 NSMutableArray 在动态表视图中添加搜索,实际上我正在使用 json 在表中添加产品,所以我需要 NSMutableArray

首先我按原样分配值

var filteredItems = [String]()
var searchController:UISearchController!
var products:NSMutableArray = NSMutableArray()

我正在使用 moltin API 并按原样使用 NSArray..

        if let newProducts:NSArray = response?["result"] as? NSArray {
            self.products.addObjects(from: newProducts as [AnyObject])

        }


        let responseDictionary = NSDictionary(dictionary: response!)

        if let newOffset:NSNumber = responseDictionary.value(forKeyPath: "pagination.offsets.next") as? NSNumber {
            self.paginationOffset = newOffset.intValue

我也用这个做单元格

let cell = tableView.dequeueReusableCell(withIdentifier: CELL_REUSE_IDENTIFIER, for: indexPath) as! ProductsListTableViewCell

    let row = (indexPath as NSIndexPath).row



let product:NSDictionary = products.object(at: row) as! NSDictionary

    cell.configureWithProduct(product)

    return cell

鉴于确实加载了导航栏上的搜索栏,我使用了正确的方法。

我正在使用这个函数来过滤结果,但是它不起作用并报错:

无法将值转换为类型 (_) -> _ 转换为接受的参数类型 'NSPredict'

func updateSearchResults(for searchController: UISearchController) {
    filteredItems.removeAll(keepingCapacity: false)

    // filter
    filteredItems = products.filter{
        item in

        item.lowercased().contains(searchController.searchBar.text!.lowercased())
    }

    tableView.reloadData()

}

但是当我使用简单的项目数组时,它对我来说效果很好。我如何在 NSMutableArray 中使用它?

【问题讨论】:

  • 您的products 包含什么?只有String(NSString)?
  • 实际上我使用 moltin API 作为 DB 并使用 NSArray
  • 我不知道 moltin API,因此无法了解 你们的产品包含什么。
  • ` if let newProducts:NSArray = response?["result"] as? NSArray { self.products.addObjects(from: newProducts as [AnyObject]) }
  • 如何将我的代码图片发送给您,以便您了解我的问题??

标签: ios swift uitableview nsmutablearray


【解决方案1】:

首先,使用json并不意味着你需要NSMutableArray。

我会将您的代码重写为:

(假设 response 是 NSDictionary? 并且 response["result"] 是一个字符串数组。如果这个假设不符合您的情况,您可能需要添加一些关于什么 response["result"] 的更多信息包含。)

var products: [String] = []

和:

    if let newProducts = response?["result"] as? [String] {
        self.products.append(contentsOf: newProducts)
    }

通过此更改,您的filteredItems = ... 无需任何修改即可工作。


如果你坚持使用NSMutableArray,你可能需要这样写:

    filteredItems = (products as NSArray as! [String]).filter {
        item in

        item.lowercased().contains(searchController.searchBar.text!.lowercased())
    }

或者这个:

    filteredItems = products.filter {
        item in

        (item as! String).lowercased().contains(searchController.searchBar.text!.lowercased())
    }.map{$0 as! String}

如果上述代码不能解决您的问题,您可能需要编辑您的问题以提供更多信息。

【讨论】:

  • 我理解您的回答,但在我的情况下有所不同我更新了我的问题,提供更多详细信息,请立即查看...
  • @Kamboh,看来你的products 不是一个简单字符串的数组,那么在你的代码中,item 变成了字典,lowercased 在NSDictionary 或Swift 字典中没有方法。回到第一点,你的products到底包含什么?
猜你喜欢
  • 2017-08-29
  • 1970-01-01
  • 1970-01-01
  • 2017-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-26
  • 2018-01-14
相关资源
最近更新 更多