需要帮助,使用谓词来过滤在UITableVIew中呈现数据的NSArray

时间:2019-05-01 19:40:09

标签: ios swift uitableview

我目前有NSArray可以从mySQL数据库获取其数据。

我需要基于硬编码的字符串"Customer1"

过滤此数据

以下是我到目前为止的内容:

import UIKit

class showCustomerDetails: UIViewController, UITableViewDataSource, UITableViewDelegate, FeedDetailProtocol  {



    var feedItems: NSArray = NSArray()
    var selectedStock : DetailModel = DetailModel()


    @IBOutlet weak var stockResultsFeed: UITableView!


    override func viewDidLoad() {
        super.viewDidLoad()


        self.stockResultsFeed.delegate = self
        self.stockResultsFeed.dataSource = self

        let detailModel = FeedDetail()
        detailModel.delegate = self
        detailModel.downloadItems()

    }
    func itemsDownloaded(items: NSArray) {

        feedItems = items
        self.stockResultsFeed.reloadData()
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // Return the number of feed items
        return feedItems.count

    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        // Retrieve cell
        let cellIdentifier: String = "customerDetails"
        let myCell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)!
        myCell.textLabel?.textAlignment = .center
        // Get the stock to be shown
        let item: DetailModel = feedItems[indexPath.row] as! DetailModel



        // Configure our cell title made up of name and price
        let customerDetails = [item.code, item.manufacturer, item.model].compactMap { $0 }.joined(separator: " — ")



        print(customerDetails)
        // Get references to labels of cell
        myCell.textLabel!.text = customerDetails

        return myCell
    }


}

以下是我的想法,但我不确定如何正确应用它:

let searchString = "Customer1"
let predicate = NSPredicate(format: "SELF contains %@", searchString)
let searchDataSource = feedItems.filter { predicate.evaluateWithObject($0) }

然后:

let item: DetailModel = searchDataSource[indexPath.row] as! DetailModel

NSArray数据来自:

import Foundation

protocol FeedDetailProtocol: class {
    func itemsDownloaded(items: NSArray)
}


class FeedDetail: NSObject, URLSessionDataDelegate {



    weak var delegate: FeedDetailProtocol!

    let urlPath = "https://www.example.com/test1/test1.php"

    func downloadItems() {

        let url: URL = URL(string: urlPath)!
        let defaultSession = Foundation.URLSession(configuration: URLSessionConfiguration.default)

        let task = defaultSession.dataTask(with: url) { (data, response, error) in

            if error != nil {
                print("Error")
            }else {
                print("details downloaded")
                self.parseJSON(data!)
            }

        }

        task.resume()
    }

    func parseJSON(_ data:Data) {

        var jsonResult = NSArray()

        do{
            jsonResult = try JSONSerialization.jsonObject(with: data, options:JSONSerialization.ReadingOptions.allowFragments) as! NSArray

        } catch let error as NSError {
            print(error)

        }

        var jsonElement = NSDictionary()
        let stocks = NSMutableArray()

        for i in 0 ..< jsonResult.count
        {

            jsonElement = jsonResult[i] as! NSDictionary

            let stock = DetailModel()

            //the following insures none of the JsonElement values are nil through optional binding
            if let code = jsonElement[“code”] as? String,
                let customer = jsonElement["customer"] as? String,
                let manufacturer = jsonElement["manufacturer"] as? String,
                let model = jsonElement["model"] as? String

            {
                print(code)
                print(manufacturer)
                print(model)
                print(customer)
                stock.code = code
                stock.manufacturer = manufacturer
                stock.model = model
                stock.customer = customer

            }

            stocks.add(stock)

        }

        DispatchQueue.main.async(execute: { () -> Void in

            self.delegate.itemsDownloaded(items: stocks)

        })
    }
}

1 个答案:

答案 0 :(得分:0)

这是Swift。使用Array而非NSArray,只需调用Array的filter方法即可。 NSArray属于Cocoa和Objective-C;您应尽可能使用本机Swift类型和Swift方法。

如果您坚持使用Cocoa Objective-C方法过滤NSArray,并且坚持使用NSPredicate,则最简单的方法是使用init(block:)构成谓词。

这是一个简单的例子:

    let arr = ["Manny", "Moe", "Jack"] as NSArray
    let p = NSPredicate { element, _ in
        return (element as? String)?.contains("a") ?? false
    }
    let arr2 = arr.filtered(using: p)
    print(arr2) // [Manny, Jack]

但是(为了说明问题)在本机Swift中要简单得多:

    let arr = ["Manny", "Moe", "Jack"]
    let arr2 = arr.filter {$0.contains("a")}