“文档” 菜单
文档首页
/ /
Atlas Device SDKs
/

在 Xcode Playgrounds 中使用 Realm

在此页面上

  • 先决条件
  • 创建 Playground
  • 导入 Realm
  • 使用 Realm 进行实验
  • 管理 Playground 中的 Realm 文件

您只能在至少具有一个模式和目标的 Xcode 项目中使用 Swift 包。要在 Xcode Playgrounds 中使用 Realm,必须首先有一个 Xcode 项目,其中已安装了 Swift SDK。

提示

另请参阅:其他快速入门和教程

有关 Realm 和 Swift 或 SwiftUI 入门的更多指导,请参阅以下快速入门或教程:

在项目中,Go到 File > New > Playground 。 选择所需的 Playground 类型。 在此示例中,我们使用了空白 iOS Playground。

Xcode Playground iOS 类型的屏幕截图,其中选择了“空白”
点击放大

命名 Playground 并将其保存在项目的根目录中。 请务必将其添加到项目中:

文件导航器的屏幕截图,其中包含 Playground 文件名和所选项目
点击放大

您应该会在项目导航器中看到新的 Playground。

Xcode 项目导航器中名为 RealmPlayground.playground 的文件的屏幕截图
点击放大

添加以下声明以在 Playground 中使用 Realm:

import RealmSwift

使用 Realm 进行试验。 对于本示例,我们将:

class Drink: Object {
@Persisted var name = ""
@Persisted var rating = 0
@Persisted var source = ""
@Persisted var drinkType = ""
}
let drink = Drink(value: ["name": "Los Cabellos", "rating": 10, "source": "AeroPress", "drinkType": "Coffee"])
let realm = try! Realm(configuration: config)
try! realm.write {
realm.add(drink)
}
let drinks = realm.objects(Drink.self)
let coffeeDrinks = drinks.where {
$0.drinkType == "Coffee"
}
print(coffeeDrinks.first?.name)

在 Playground 中使用默认域时,可能会遇到需要删除该域的情况。例如,如果您正在试验一种Realm 对象类型并向该对象添加属性,则可能会收到必须迁移 域 的错误消息。

您可以指定Realm.configuration详细信息以打开特定路径中的文件,并删除该路径中存在的 Realm(如果存在)。

var config = Realm.Configuration()
config.fileURL!.deleteLastPathComponent()
config.fileURL!.appendPathComponent("playgroundRealm")
config.fileURL!.appendPathExtension("realm")
if Realm.fileExists(for: config) {
try Realm.deleteFiles(for: config)
print("Successfully deleted existing realm at path: \(config.fileURL!)")
} else {
print("No file currently exists at path")
}

或者,您可以仅在内存中打开Realm,或使用deleteRealmIfMigrationNeeded方法在需要迁移时自动删除 Realm。

后退

基于分区的同步

来年

SDK 遥测