通过视图更新 swift 领域对象

问题描述 投票:0回答:1

在 Real Swift 项目中,我想通过视图更新 Realm 对象。因此 Realm 对象是一个类,我只想通过方法进行通信。我的看法是这样的:

struct ViewBook: View {
    @ObservedRealmObject var book: Book
    @State var text: String

    init(book: Book){
        self.book = book
        self.text = ""
    }

    func nextPage(){    
            let realm = book.thaw()!.realm!
            
            let thawedBook = self.book.thaw()!
            try! realm.write{
                self.text = thawedBook.getNextChapter()
    }
}

这使用了一个书籍对象,该对象存储在数据库中,如下所示。

class Book: Object ,ObjectKeyIdentifiable ,Identifiable, Codable{
    @Persisted var chapterList: SpeedReader.chapterList?

    func getNextChapter() -> String{
        self.text = chapterList!.getNextChapter()
        return text
    }
}
class chapterList: Object, Codable{
    @Persisted var _list: RealmSwift.List<chapter>
    @Persisted var _currentChapter: chapter? = chapter()
    @Persisted var _indexChapter = 0

    func getNextChapter() -> String {
        do {
            let realm = self.realm!.thaw()
            try realm.write{
                self.thaw()?._indexChapter += 1
            }
        } catch {
            print("Error in Chapterlist", error)
        }
        
        return self._list[_indexChapter].getText()
    }
}
class chapter: Object, Codable{
    @Persisted var htmlString = ""

    func getText() -> String{
        return self.htmlString
    }
}

我的想法是单击视图中的按钮,该按钮会更新书籍和章节列表,最后将新文本返回到视图。

使用我当前的代码,我收到错误

[General] The Realm is already in a write transaction

我不知道这是否有帮助,使用一些替代代码,不幸的是我没有保存,我收到了错误

[General] Attempting to modify a frozen object - call thaw on the Object instance first.

[General] Can't perform transactions on a frozen realm
swift swiftui realm
1个回答
0
投票

这就是发生错误的原因

当调用

nextPage
时,它会打开一个写事务

func nextPage(){
   try! realm.write {
      self.text = thawedBook.getNextChapter()

在写入过程中,在(书)上调用

.getNextChapter
thawedBook

class Book: Object ,ObjectKeyIdentifiable ,Identifiable, Codable{
    func getNextChapter() -> String{
       self.text = chapterList!.getNextChapter()

.getNextChapter
对象上调用
chapterList

class chapterList: Object, Codable{
   func getNextChapter() -> String {
      do {
         let realm = self.realm!.thaw()
         try realm.write{
             self.thaw()?._indexChapter += 1

尝试打开另一个写事务,因此出现错误。

我没有看到任何理由在

nextPage
内打开写入,因此删除它可以解决该特定问题。

一些(希望有帮助的)观察;

  1. 一般来说,一本书有可以由两个对象表示的章节 - 代码还实现了一个中间对象

    chapterList
    ,它似乎没有任何用途。我的建议是让章节成为本书的
    List
    属性,这样会更容易管理;更新查询等。此外,当前章节或页面也可以是书籍的属性。

  2. 正在进行大量解冻,这本身就很难管理。一种选择是使用隐式写入,因为 Book 是一个 @ObservedRealmObject,请参阅快速写入

  3. 编码的最佳实践是将类、结构和枚举大写,这使得阅读和理解代码更加清晰,因为有一个可见的指示符来区分类和 var(应始终小写)

class ChapterList: Object, Codable {
   ...
© www.soinside.com 2019 - 2024. All rights reserved.