ios - 在 Swift 中将 AnyObject 添加到 NSMutableArray

标签 ios swift uitableview nspredicate

我只是想进行 Tableview 搜索。我正在使用 NSPredicate 进行搜索。

每个教程的人都给出了这行代码:

let resultPredicate = NSPredicate(format: "SELF contains[c] %@", searchText)
self.nameArray = self.nameArray.filteredArrayUsingPredicate(resultPredicate)

但在第二行 Xcode 说:无法将类型为“[AnyObject]”的值分配给类型为“NSMutableArray”的值

我尝试转换,但这次 xcode 建立了 nil 值。我的两个数组都是 NSMutableArray。有什么建议吗?

编辑

我的手 secret 码:

let cell:ItemsTVCell = tableView.dequeueReusableCellWithIdentifier("CELL") as! ItemsTVCell

    if tableView == self.searchDisplayController?.searchResultsTableView {
        cell.itemNameLabel.text = filteredArray[indexPath.row] as? String
    } else {
        cell.itemNameLabel.text = nameArray[indexPath.row] as? String
    }

    return cell

最佳答案

filteredArrayUsingPredicate 返回 [AnyObject],看起来您的属性属于 NSMutableArray 类型。您有几个选项,按优先顺序排列:

  • 将您的属性更改为 Swift 数组(例如 var nameArray: [String])而不是 NSMutableArray。不使用 filteredArrayUsingPredicate,而是使用数组的过滤方法:

    self.nameArray = self.nameArray.filter({contains($0.lowercaseString, searchText.lowercaseString})

  • 如果您必须继续将您的属性保留为 NSMutableArray,您可以使用过滤后的数组的内容创建 NSArray 的实例:

    NSMutableArray(array: self.nameArray.filteredArrayUsingPredicate(resultPredicate))

关于ios - 在 Swift 中将 AnyObject 添加到 NSMutableArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31641135/

相关文章:

swift - 为 TableView Cell Swift 插入单个背景图像

swift - 删除在 UITableViewController 中不起作用的行

ios - 在 UIViewController Extension 中引用全局字符串变量

ios - 函数无法正确执行(Swift 3)

ios - 如何通过 segue - Swift 从结构对象数组发送变量

ios - 未调用 deinit 的解释

swift - Swift 中常见的父 View

arrays - 将 SearchBar 添加到 uitableview 在过滤过程中遇到错误

iphone - 在 UITableView 中使用多种单元格样式类型和自定义单元格

ios - IOS SDK 使用命令行生成构建时出错?