定义领域数据库结构(快速)

时间:2018-09-02 02:00:16

标签: ios swift database realm

我正在创建一个应用程序,该应用程序将显示用户保存在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添加到用户数组的能力。

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分: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()
}