gpt4 book ai didi

swift - Realm 提交写入错误 - 无法提交不存在的写入事务

转载 作者:搜寻专家 更新时间:2023-10-31 21:59:24 25 4
gpt4 key购买 nike

我正在尝试向 Realm 数据库表中添加一条记录。

我有一个 Connection 类,它代表我在我的数据库中需要的一个表,并创建了代表列的动态变量:

import Foundation
import RealmSwift
import Realm

open class ConnectionState: Object {

open dynamic var _id : String = NSUUID().uuidString
open dynamic var a : String = ""
open dynamic var b : String = ""
open dynamic var c : Int = 0

open override class func primaryKey() -> String? {
return "_id"
}

required public init() {
super.init()
}

required public init(realm: RLMRealm, schema: RLMObjectSchema) {
super.init(realm: realm, schema: schema)
}

required public init(value: Any, schema: RLMSchema) {
fatalError("init(value:schema:) has not been implemented")
}
}

然后在我的代码中,我尝试像这样编写和提交写入事务:

let ConnectionState = ConnectionState()
ConnectionState.a = "a"
ConnectionState.b = "b"
ConnectionState.c = 1
try! self.realm.write {
self.realm.add(ConnectionState)
}

try! self.realm.commitWrite()

运行这段代码时,我收到错误:

Can't commit a non-existing write transaction

我错过了什么?我的 ConnectionState 类中是否需要初始化?在添加 commitWrite 之前,我试图用 Realm 浏览器查看数据库。我在 xCode 中找到我的设备并选择下载容器,但它是空的。然后我想我需要在 commitWrite 中添加

最佳答案

在您的示例中,您调用了 commitWrite 而没有调用 beginWrite。您不能提交写入事务,因为您没有启动一个事务。启动写入事务或删除 commitWrite 行。

  1. 开始事务并提交

    self.realm.beginWrite()

    self.realm.add(ConnectionState)

    try! self.realm.commitWrite()
  2. 删除提交写入

    try! self.realm.write {
    self.realm.add(ConnectionState)
    }

Realm docs有两个向数据库添加数据的例子。

  1. 使用realm.write方法

    // Use them like regular Swift objects
    let myDog = Dog()
    myDog.name = "Rex"
    myDog.age = 1
    print("name of dog: \(myDog.name)")

    // Get the default Realm
    let realm = try! Realm()

    // Query Realm for all dogs less than 2 years old
    let puppies = realm.objects(Dog.self).filter("age < 2")
    puppies.count // => 0 because no dogs have been added to the Realm yet

    // Persist your data easily
    try! realm.write {
    realm.add(myDog)
    }
  2. 使用realm.beginWrite()realm.commitWrite() 开始写入事务并将数据提交到数据库

    let realm = try! Realm()

    // Break up the writing blocks into smaller portions
    // by starting a new transaction
    for idx1 in 0..<1000 {
    realm.beginWrite()

    // Add row via dictionary. Property order is ignored.
    for idx2 in 0..<1000 {
    realm.create(Person.self, value: [
    "name": "\(idx1)",
    "birthdate": Date(timeIntervalSince1970: TimeInterval(idx2))
    ])
    }

    // Commit the write transaction
    // to make this data available to other threads
    try! realm.commitWrite()
    }

关于swift - Realm 提交写入错误 - 无法提交不存在的写入事务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41588230/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com