0

我刚刚使用 Realm 数据库构建了一个简单的 Todo 应用程序。我使用从 Mac Apple Store 下载的 Realm Browser 2.1.6 来保存数据。通过使用Realm Browser,我可以正常编辑现有记录的值并显示在Todo App屏幕上,但是(Command +)添加的新记录无法显示在模拟器屏幕上。我正在使用 Xcode 8.2 和 swift 3。我错过了什么还是这是一个错误?

谢谢你的工作。

我最诚挚的问候,

鸭川

4

1 回答 1

0

如果您添加到 Realm Browser 的那些新对象确实已经存在(即,您可以关闭 Realm 文件并重新打开它,它们仍然存在),那么听起来您需要在其中添加一个通知块您的应用程序可以检测 Realm Browser 何时更改数据并触发 UI 更新。

如果您将这些记录显示为表格或集合视图,则可以使用Realm 的集合更改通知来检测何时添加了新对象。

class ViewController: UITableViewController {
  var notificationToken: NotificationToken? = nil

  override func viewDidLoad() {
    super.viewDidLoad()
    let realm = try! Realm()
    let results = realm.objects(Person.self).filter("age > 5")

    // Observe Results Notifications
    notificationToken = results.addNotificationBlock { [weak self] (changes: RealmCollectionChange) in
      guard let tableView = self?.tableView else { return }
      switch changes {
      case .initial:
        // Results are now populated and can be accessed without blocking the UI
        tableView.reloadData()
        break
      case .update(_, let deletions, let insertions, let modifications):
        // Query results have changed, so apply them to the UITableView
        tableView.beginUpdates()
        tableView.insertRows(at: insertions.map({ IndexPath(row: $0, section: 0) }),
                           with: .automatic)
        tableView.deleteRows(at: deletions.map({ IndexPath(row: $0, section: 0)}),
                           with: .automatic)
        tableView.reloadRows(at: modifications.map({ IndexPath(row: $0, section: 0) }),
                           with: .automatic)
        tableView.endUpdates()
        break
      case .error(let error):
        // An error occurred while opening the Realm file on the background worker thread
        fatalError("\(error)")
        break
      }
    }
  }

  deinit {
    notificationToken?.stop()
  }
}

如果没有,那么您可能需要使用另一种类型的 Realm 通知。

在任何情况下,即使您的应用程序中的 UI 没有更新,Realm 对象也是实时的,并且会在它们的值更改时自动更新。您应该能够在您的应用程序中设置断点并直接检查对象以确认您的数据正在出现。祝你好运!

于 2017-03-21T23:05:46.140 回答