将数组保存到CoreData Swift

时间:2018-03-02 20:31:26

标签: ios arrays swift core-data persistence

我想将这种arraysCore Data

一起保存
let crypto1 = Cryptos(name: "Bitcoin", code: "bitcoin", symbol: "BTC", placeholder: "BTC Amount", amount: "0.0")
let crypto2 = Cryptos(name: "Bitcoin Cash", code: "bitcoinCash", symbol: "BCH", placeholder: "BCH Amount", amount: "0.0")

这甚至可能吗?

我知道我可以创建一个像这样保存的数组......

let name = "Bitcoin"
let code = "bitcoin"
let symbol = "BTC"
let placeholder = "BTC Amount"
let amount = "0.0"
let cryptos = CryptoArray(context: PersistenceService.context)
cryptos.name = name
cryptos.code = code
cryptos.symbol = symbol
cryptos.placeholder = placeholder
cryptos.amount = amount
crypto.append(cryptos)
PersistenceService.saveContext()

...但是当用户创建理论上无限数量的数组时,这似乎很不方便。

对我来说,保存数据,加载,编辑和删除数据的最佳方式是什么?

1 个答案:

答案 0 :(得分:2)

您无法使用CoreData直接保存数组,但您可以创建一个函数来存储数组的每个对象。使用CoreStore,整个过程非常简单:

let dataStack: DataStack = {
    let dataStack = DataStack(xcodeModelName: "ModelName")
    do {
        try dataStack.addStorageAndWait()
    } catch let error {
        print("Cannot set up database storage: \(error)")
    }
    return dataStack
}()

func addCrypto(name: String, code: String, symbol: String, placeholder: String, amount: Double) {
    dataStack.perform(asynchronous: { transaction in
        let crypto = transaction.create(Into<Crypto>())
        crypto.name = name
        crypto.code = code
        crypto.symbol = symbol
        crypto.placeholder = placeholder
        crypto.amount = amount
    }, completion: { _ in })
}

您可以在UITableViewController内显示对象。只要添加,删除或更新数据库对象,CoreStore就能自动更新表:

class CryptoTableViewController: UITableViewController {

    let monitor = dataStack.monitorList(From<Crypto>(), OrderBy(.ascending("name")), Tweak({ fetchRequest in
        fetchRequest.fetchBatchSize = 20
    }))

    override func viewDidLoad() {
        super.viewDidLoad()
        // Register self as observer to monitor
        self.monitor.addObserver(self)
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.monitor.numberOfObjects()
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CryptoTableViewCell", for: indexPath) as! CryptoTableViewCell
        let crypto = self.monitor[(indexPath as NSIndexPath).row]
        cell.update(crypto)
        return cell
    }

}

// MARK: - ListObjectObserver

extension CryptoTableViewController : ListObjectObserver {

    // MARK: ListObserver

    func listMonitorWillChange(_ monitor: ListMonitor<Crypto>) {
        self.tableView.beginUpdates()
    }

    func listMonitorDidChange(_ monitor: ListMonitor<Crypto>) {
        self.tableView.endUpdates()
    }

    func listMonitorWillRefetch(_ monitor: ListMonitor<Crypto>) {
    }

    func listMonitorDidRefetch(_ monitor: ListMonitor<Crypto>) {
        self.tableView.reloadData()
    }

    // MARK: ListObjectObserver

    func listMonitor(_ monitor: ListMonitor<Crypto>, didInsertObject object: Switch, toIndexPath indexPath: IndexPath) {
        self.tableView.insertRows(at: [indexPath], with: .automatic)
    }

    func listMonitor(_ monitor: ListMonitor<Crypto>, didDeleteObject object: Switch, fromIndexPath indexPath: IndexPath) {
        self.tableView.deleteRows(at: [indexPath], with: .automatic)
    }

    func listMonitor(_ monitor: ListMonitor<Crypto>, didUpdateObject object: Crypto, atIndexPath indexPath: IndexPath) {
        if let cell = self.tableView.cellForRow(at: indexPath) as? CryptoTableViewCell {
            cell.update(object)
        }
    }

    func listMonitor(_ monitor: ListMonitor<Crypto>, didMoveObject object: Switch, fromIndexPath: IndexPath, toIndexPath: IndexPath) {
        self.tableView.deleteRows(at: [fromIndexPath], with: .automatic)
        self.tableView.insertRows(at: [toIndexPath], with: .automatic)
    }

}

假设您CryptoTableViewCell的{​​{1}}函数已注册update