【问题标题】:Defining a Realm Database Structure (Swift)定义领域数据库结构 (Swift)
【发布时间】:2018-09-02 02:00:15
【问题描述】:

我正在创建一个应用程序,该应用程序将显示用户保存在 tableView 中的股票列表。它还将允许用户从他们的收藏夹中添加或删除项目。我需要帮助定义数据库结构并设置用户最喜欢的股票的添加和不断更新。

我目前有一个与我的 tableView 一起使用的 StockData 结构和一个用于添加到用户列表的按钮:

struct StockData {
    let currentPrice: Double    
    // meta data
    let name: String
    let ticker: String
    let interval: String
    let lastRefreshed: String
    let change: Double 
}

// In an actual ViewController
@IBAction func addButtonClicked(_ sender: Any) {
    print("Add clicked")
    // Handle adding the item to the user's list
}

现在就我当前的领域模型而言,我有:

class User: Object {
    @objc dynamic var name = ""
    @objc dynamic var id = ""

    var stockFavs = List<StockItem>()
}

class StockItem: Object {
    @objc dynamic var currentPrice: Double = 0.0
    // meta data
    @objc dynamic var name = ""
    @objc dynamic var ticker = ""
    @objc dynamic var interval = ""
    @objc dynamic var lastRefreshed = ""
    @objc dynamic var change: Double = 0.0
}

// Setting up the user and creating test values
        let newUser = User()
        newUser.name = "John Smith"
        newUser.id = "coolId123"

        var stockArr = List<StockItem>()
        for i in 0..<12 {
            let item = StockItem()
            item.name = "Microsoft Corporation"
            item.change = -3.55
            item.currentPrice = 123.45
            item.interval = "1day"
            item.lastRefreshed = "Now"
            item.ticker = "MSFT"
            stockArr.append(item)
        }

        newUser.stockFavs = stockArr

        try! realm.write {
            realm.add(newUser)
        }

到目前为止,我已经能够为设备的当前用户创建一个用户对象并添加测试值,但我不确定如何实现恒定领域更新(该方法将具有self.tableView.reloadData(),但除此之外,我一无所知)以及将StockItem's 添加到用户数组的能力。

任何帮助将不胜感激!

【问题讨论】:

    标签: ios swift database realm


    【解决方案1】:

    您每次想要添加到数据库时都使用一个函数。

    let button = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 100)
    button.addTarget(self, action: #selector(add), for: .touchUpInside)
    
    func add() {
      let currentData = [MyFakeData1, MyFakeData2, etc.]
      try! realm.write {
        realm.add(currentData)
      }
      // You need to get the updates in the database
      // You could have an array in your model that you update and then append all
      // the new items to it and only do database lookups when you restart the 
      // device
      update()
    }
    
    func update() {
      let realm = try! Realm()
      var newArray = realm.objects(StockItem.self)
      myViewController.modelArray = newArray
      table.reloadData()
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-25
      • 1970-01-01
      • 1970-01-01
      • 2019-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多