使用Swift进行核心数据指导3

时间:2016-12-31 22:40:46

标签: ios json swift uitableview core-data

不寻找代码(不会伤害)只是想知道我应该怎么做。我有一个像博客阅读器的应用程序。我在MYSQL数据库中有信息,该数据库使用JSON,放在jsonArray中,然后放在一个数组中以显示在表视图中。在该表视图中,我通常将所有对象放在1节中。每个行/对象在单击时都有一个按钮,它将该行移动到另一个部分。我还有一个搜索控制器来搜索主要部分(第1节)。

如何将行的顺序或位置保存到Core Data?

例如:我在第0部分中有0行,第1部分中有5行,我单击第1部分中某一行上的按钮,然后将该行移动到第0部分,现在部分0有1行而第1部分有4行。如何将此新的tableview订单保存到Core Data?我只想保存行位置,因此应用程序会记住所选行的哪个部分。

我是否在该部分中保存该行的indexPath? 添加实体和属性时,我用什么来保存?

另外,它是一个mysql阅读器,所以当重新加载tableview并添加新内容时,它是否仍会显示,因为tableview将从核心数据中读取?

我正在学习核心数据(Swift 3代码),但在使用此应用程序时遇到了麻烦。

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

如果您不需要保存MySQL数据库中的全部数据,请使用UserDefaults保存订购数据。定义一个只包含dataId和indexPath的类:

class DataOrdering: NSObject, NSCoding {

    var indexPath: IndexPath?
    var dataId: String?

    init(dataId: String, indexPath: IndexPath) {
        super.init()
        self.dataId = dataId
        self.indexPath = indexPath
    }

    required init(coder aDecoder: NSCoder) {

        if let dataId = aDecoder.decodeObject(forKey: "dataId") as? String {
            self.dataId = dataId
        }

        if let indexPath = aDecoder.decodeObject(forKey: "indexPath") as? IndexPath {
            self.indexPath = indexPath
        }

    }

    func encode(with aCoder: NSCoder) {
        aCoder.encode(dataId, forKey: "dataId")
        aCoder.encode(indexPath, forKey: "indexPath")
    }

    func save(defaults key: String) -> Bool {

        let defaults = UserDefaults.standard
        let savedData = NSKeyedArchiver.archivedData(withRootObject: self)
        defaults.set(savedData, forKey: key)
        return defaults.synchronize()

    }

    convenience init?(defaults key: String) {

        let defaults = UserDefaults.standard
        if let data = defaults.object(forKey: key) as? Data,
            let obj = NSKeyedUnarchiver.unarchiveObject(with: data) as? DataOrdering,
            let dataId = obj.dataId,
            let indexPath = obj.indexPath {
            self.init(dataId: dataId, indexPath: indexPath)
        } else {
            return nil
        }

    }

    class func allSavedOrdering(_ maxRows: Int) -> [Int: [DataOrdering]] {

        var result: [Int: [DataOrdering]] = [:]
        for section in 0...1 {
            var rows: [DataOrdering] = []
            for row in 0..<maxRows {
                let indexPath = IndexPath(row: row, section: section)
                if let ordering = DataOrdering(defaults: indexPath.defaultsKey) {
                    rows.append(ordering)
                }
                rows.sort(by: { $0.indexPath! < $1.indexPath! })
            }
            result[section] = rows
        }

        return result

    }

}

游乐场样本:

let data = DataOrdering(dataId: "1", indexPath: IndexPath(row: 0, section: 0))

let savedData = NSKeyedArchiver.archivedData(withRootObject: data)
let obj = NSKeyedUnarchiver.unarchiveObject(with: savedData) as? DataOrdering
obj?.dataId // print: "1"
obj?.indexPath // print: [0,0]

使用保存功能保存“key”并通过DataOrdering读取(默认值:“key”)

<强>已更新

添加了视图控制器的代码以使用此类:

extension IndexPath {
    var defaultsKey: String { return "data_ordering_\(section)_\(row)" }
}

class ViewController: UITableViewController {

    var data: [Any]?
    var items: [[Any]]?

    func fetchData() {

        // request from remote or local
        data = [1, 2, 3, "a", "b", "c"] // sample data

        // Update the items to first section has 0 elements,
        // and place all data in section 1
        items = [[], data ?? []]

        // apply ordering
        applySorting() { "\($0)" }

        // save ordering
        saveSorting() { "\($0)" }

        // refresh the table view
        tableView.reloadData()

    }

    func applySorting(_ dataIdBlock: (Any) -> String) {

        // get all saved ordering
        guard let data = self.data else { return }
        let ordering = DataOrdering.allSavedOrdering(data.count)

        var result: [[Any]] = [[], []]

        for (section, ordering) in ordering {
            guard section <= 1 else { continue } // make sure the section is 0 or 1
            let rows = data.filter({ obj -> Bool in
                return ordering.index(where: { $0.dataId == .some(dataIdBlock(obj)) }) != nil
            })
            result[section] = rows
        }

        self.items = result

    }

    func saveSorting(_ dataIdBlock: (Any) -> String) {

        guard let items = self.items else { return }

        for (section, rows) in items.enumerated() {
            for (row, item) in rows.enumerated() {
                let indexPath = IndexPath(row: row, section: section)
                let dataId = dataIdBlock(item)
                let ordering = DataOrdering(dataId: dataId, indexPath: indexPath)
                ordering.save(defaults: indexPath.defaultsKey)
            }
        }

    }

    @IBAction func buttonMoveToSectionTapped(_ sender: UIButton) {

        // if the sender's tag is row index
        // or you can get indexPath by tableView.indexPath(for: cell) function too
        let row = sender.tag

        // move this item from section 1 to section 0 (last position)
        if let item = items?[1].remove(at: row) {
            items?[0].append(item)
        }

        // Save all sorting
        saveSorting() { "\($0)" }

        tableView.reloadData() // refresh table view

    }

    override func numberOfSections(in tableView: UITableView) -> Int {
        return self.items?.count ?? 0
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.items?[section].count ?? 0
    }


}