菜鸟教程小白 发表于 2022-12-12 12:56:33

ios - Realm 是什么样的数据库?


                                            <p><p><strong>Realm</strong> 是什么类型的数据库?是 <strong>ORM</strong> 吗?还是它像对象数据库一样工作?也许数据库结构会以某种方式影响设计过程?设计 Realm 数据库有什么细微差别吗?</p>

<p>我在这里问,因为我在官网上没有找到答案</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>不幸的是,我实际上并没有使用 <strong>iOS</strong> 版本,但我使用的是 Android 版本,它的功能集与 iOS 版本越来越相似,并且他们共享相同的 <code>core</code>,它们更接近于通过 <code>object-store</code> 提供相同的统一行为。</p>

<p>因此,此答案的大部分将基于 Swift API 文档。 (境界迅捷
2.6.1)</p>

<hr/>

<p>Realm 默认是一个对象存储。从技术上讲,它将您的数据存储在架构中,其中架构由类定义,例如</p>

<pre><code>// from https://realm.io/docs/swift/latest/#models
class Person: Object {
    dynamic var name = &#34;&#34;
    dynamic var birthdate = NSDate(timeIntervalSince1970: 1)
    let dogs = List&lt;Dog&gt;()
}
</code></pre>

<p>Realm 的有趣之处在于它不是一个关系型数据库。它直接存储对象。实际上,由 Realm 管理的对象(也就是通过对 Realm 的查询获得的,或者由 Realm 创建的新对象)直接映射到底层 Realm 文件,并且不会将数据复制到字段,访问器直接读取和写入 Realm 文件。</p>

<p>这种“直接访问”导致所有数据仅在访问时加载(延迟评估),因此不需要缓存托管对象(!)。</p>

<p>所有写入都是事务性的。在事务之外,托管的 RealmObjects 不能被修改。</p>

<hr/>

<p>在您的对象之间,您可以拥有<em>关系</em>(链接):</p>

<pre><code>// from https://realm.io/docs/swift/latest/#relationships
class Dog: Object {
    // ... other property declarations
    dynamic var owner: Person? // to-one relationships must be optional
}

class Person: Object {
    // ... other property declarations
    let dogs = List&lt;Dog&gt;() // to-many relationship
}
</code></pre>

<p>任何关系(一对一、对多)都有其对应的<code>backlink</code>,您可以将其定义为“链接到该对象的对象”。</p>

<pre><code>// from https://realm.io/docs/swift/latest/#relationships
class Dog: Object {
    dynamic var name = &#34;&#34;
    dynamic var age = 0
    let owners = LinkingObjects(fromType: Person.self, property: &#34;dogs&#34;)
}
</code></pre>

<hr/>

<p>Realm 的托管对象是“实时的、不可变的数据 View ”(来自 <a href="https://realm.io/docs/swift/latest/#auto-updating-objects" rel="noreferrer noopener nofollow">here</a>),它<strong>在原地发生变异,并且您通过 <code>通知 token </code></strong>(来自 <a href="https://realm.io/docs/swift/latest/#notifications" rel="noreferrer noopener nofollow">here</a>)。这同样适用于<em>任何托管的 RealmObject</em>,但<strong>也适用于查询结果</strong>。 </p>

<p>意思是,查询结果会自动进行异步评估,并且只有在给定索引处访问的元素才会以延迟加载的方式从数据库中读取!因此,不需要分页。</p>

<p><strong>任何线程上的任何写入都会自动向与运行循环关联的线程发送通知,查询结果会自动更新,并调用更改监听器(通知 block )。</strong></p >

<pre><code>// from https://realm.io/docs/swift/latest/#collection-notifications
override func viewDidLoad() {
    super.viewDidLoad()
    let realm = try! Realm()
    let results = realm.objects(Person.self).filter(&#34;age &gt; 5&#34;)

    // Observe Results Notifications
    notificationToken = results.addNotificationBlock { (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(&#34;\(error)&#34;)
      break
      }
    }
}

deinit {
    notificationToken?.stop()
}
</code></pre>

<hr/>

<p>最广为人知的限制是 RealmObjects、RealmResults 和 Realms<em>不能在线程之间传递</em>。 (其他限制为 <a href="https://realm.io/docs/swift/latest/#current-limitations" rel="noreferrer noopener nofollow">here</a>)。</p>

<p>给定线程上的 RealmObject/RealmResults/Realm 只能在打开其对应 Realm 实例的线程上访问(读取 <a href="https://realm.io/docs/swift/latest/#threading" rel="noreferrer noopener nofollow">here</a>)。 (异常(exception)情况是使用 <code>ThreadSafeReference</code> 在线程之间发送 RealmObjects,参见 <a href="https://realm.io/docs/swift/latest/#passing-instances-across-threads" rel="noreferrer noopener nofollow">here</a>。</p>

<p>因此,后台线程需要自己的 Realm 实例,通常包装在 <code>autoreleasepool</code> 中,参见 <a href="https://realm.io/docs/swift/latest/#using-a-realm-across-threads" rel="noreferrer noopener nofollow">here</a> .</p>

<pre><code>// from https://realm.io/docs/swift/latest/#using-a-realm-across-threads
DispatchQueue(label: &#34;background&#34;).async {
autoreleasepool {
    // Get realm and table instances for this thread
    let realm = try! Realm()

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

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

      // Commit the write transaction
      // to make this data available to other threads
      try! realm.commitWrite()
    }
}
}
</code></pre></p>
                                   
                                                <p style="font-size: 20px;">关于ios - Realm 是什么样的数据库?,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/42337312/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/42337312/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - Realm 是什么样的数据库?