无法使用从 Mac Apple Store 下载的领域浏览器 2.1.6 将新记录添加到领域数据库



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

感谢您的工作。

我最诚挚的问候,

鸭川

如果您添加到 Realm 浏览器的那些新对象确实保留了下来(也就是说,您可以关闭 Realm 文件并重新打开它,但它们仍然存在(,那么听起来您需要在应用程序中添加一个通知块来检测 Realm 浏览器何时更改了数据并触发 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 对象也是实时的,并且会在其值更改时自行自动更新。您应该能够在应用中设置断点,并直接检查对象以确认数据是否遇到。祝你好运!

相关内容

最新更新