当Realm结果更新时,TableView抛出NSInternalInconsistencyException



我在Swift中有一个Realm结果集的问题。我使用一个Realm通知块来更新我的TableView每当Realm结果更新。

然而,在更新TableView期间,有时会向Realm结果添加新项,导致NSInternalInconsistencyException .

我的环境:

    迅速
  • 3
  • 领域2.0.4
  • Xcode 8.1 (8B62)

场景:

让我们假设我正在发送一个聊天消息,同时也收到一个。

  1. 我正在添加我发送到Realm数据库的消息。
  2. 我的Realm通知块将开始更新TableView
  3. 同时,我收到了某人的聊天消息,并且它也被添加到Realm数据库中。
  4. TableView更新完成并抛出NSInternalInconsistencyException,因为更新开始时Realm的大小与更新结束时的大小不同(因为接收到的消息被添加到Realm数据库中)。
抛出的异常
2016-11-16 21:03:57.727510 MyApp[9042:2331360] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 0.  The number of rows contained in an existing section after the update (98) must be equal to the number of rows contained in that section before the update (97), plus or minus the number of rows inserted or deleted from that section (10 inserted, 10 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).'
*** First throw call stack:
(0x18f5021c0 0x18df3c55c 0x18f502094 0x18ff8f79c 0x19554001c 0x1000faeb8 0x10137619c 0x10134d4d0 0x100bf4b88 0x100bf4754 0x100b427fc 0x100b425f0 0x100ba0004 0x100d3072c 0x100d878b8 0x100d8840c 0x100d883e4 0x18f4b0278 0x18f4afbc0 0x18f4ad7c0 0x18f3dc048 0x190e62198 0x1953c82fc 0x1953c3034 0x100105be8 0x18e3c05b8)
libc++abi.dylib: terminating with uncaught exception of type NSException

复制步骤:

  1. 创建TableView控制器
  2. 使用realm.objects(ChatMessage.self)获得一些结果。
  3. 使用Realm集合通知来更新TableView
  4. 以0.1秒的间隔向Realm添加新消息
  5. 构建并运行应用程序。
  6. 等待几秒钟,应用程序崩溃与NSInternalInconsistencyException

视图控制器:

这是导致崩溃的代码。

import UIKit
import RealmSwift
import Alamofire
import AlamofireObjectMapper
class ChatTestViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    @IBOutlet weak var tableView: UITableView!
    let realm =  try! Realm()
    let textCellMeIdentifier = "ChatMessageCellMe"
    var results: Results<ChatMessage>?
    var ticket: Ticket?
    var notificationToken: NotificationToken?
    var tableViewTempCount = 0
    override func viewDidLoad() {
        super.viewDidLoad()
        ticket = realm.objects(Ticket.self).first
        results = realm.objects(ChatMessage.self)
        initializeTableView()
        notificationToken = results?.addNotificationBlock { [weak self] (changes: RealmCollectionChange) in
            guard let tableView = self?.tableView else { return }
            switch changes {
            case .initial:
                tableView.reloadData()
                break
            case .update(_, let deletions, let insertions, let modifications):
                tableView.beginUpdates()
                tableView.insertRows(at: insertions.map({ IndexPath(row: $0, section: 0) }), with: .none)
                tableView.deleteRows(at: deletions.map({ IndexPath(row: $0, section: 0)}), with: .none)
                tableView.reloadRows(at: modifications.map({ IndexPath(row: $0, section: 0) }), with: .none)
                tableView.endUpdates()
                break
            case .error(let error):
                fatalError("(error)")
                break
            }
        }
        _ = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(self.sendRandomMessage), userInfo: nil, repeats: true)
    }
    deinit {
        notificationToken?.stop()
    }
    private func initializeTableView() {
        tableView.register(UINib(nibName: textCellMeIdentifier, bundle: Bundle.main), forCellReuseIdentifier: textCellMeIdentifier)
        tableView.delegate = self
        tableView.dataSource = self
    }
    @objc func sendRandomMessage() {
        tableViewTempCount += 1
        let parameters: Parameters = [
            "body": "Random Test: " + String(describing: tableViewTempCount),
        ]
        let tempMessage = ChatMessage()
        tempMessage.id = "-" + String(describing: tableViewTempCount)
        tempMessage.ticketId = ticket!.id
        tempMessage.sent = false
        tempMessage.body = parameters["body"]! as! String
        tempMessage.by = ChatMessage.By.me.rawValue
        tempMessage.createdAt = Date()
        let realm = try! Realm()
        try! realm.write {
            /// Add a temporary message to the TableView (and remove it if the server returned the saved message)
            realm.add(tempMessage, update: true)
//            _ = ChatMessageClient.create(ticket!, parameters) { (error: Error?, chatMessages: [ChatMessage]?) in
//                /// The server responded with the message and it was inserted in our Realm database, so delete the temp message
//                realm.delete(tempMessage)
//            }
        }
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return results!.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let row = results?[indexPath.row]
        let cell:ChatMessageCell = (tableView.dequeueReusableCell(withIdentifier: textCellMeIdentifier, for: indexPath as IndexPath) as? ChatMessageCell)!
        cell.body.text = row?.body
        cell.container.alpha = (row?.sent)! ? 1.0 : 0.4
        return cell
    }
}

我希望有人能帮助我防止这个异常被抛出。

我们最近修复了Realm集合通知机制中的一些竞态条件,这些条件可能会导致您在这里看到的异常。见https://realm.io/news/realm - objc斯威夫特- 2.1/

你能不能用Realm Swift 2.1.0再试一次,然后让我们知道它是否解决了你的问题?谢谢!

最新更新