在 Xcode Playgrounds 中使用 Realm
Realm 现已更名为 Atlas Device SDK – 了解详情
先决条件
您只能在至少具有一个模式和目标的 Xcode 项目中使用 Swift 包。要在 Xcode Playgrounds 中使用 Realm,必须首先有一个 Xcode 项目,其中已安装了 Swift SDK。
创建 Playground
提示
另请参阅:其他快速入门和教程
有关 Realm 和 Swift 或 SwiftUI 入门的更多指导,请参阅以下快速入门或教程:
在项目中,Go到 File > New > Playground 。 选择所需的 Playground 类型。 在此示例中,我们使用了空白 iOS Playground。
![Xcode Playground iOS 类型的屏幕截图,其中选择了“空白”](/zh-cn/docs/atlas/device-sdks/static/4a4b782b029bf60af67e95b69ae1f43c/4cd4b/xcode-playground-blank-ios.webp)
点击放大
命名 Playground 并将其保存在项目的根目录中。 请务必将其添加到项目中:
![文件导航器的屏幕截图,其中包含 Playground 文件名和所选项目](/zh-cn/docs/atlas/device-sdks/static/c720e4241f5914a079631cb68df12d62/ab382/xcode-playgrounds-create-in-project.webp)
点击放大
您应该会在项目导航器中看到新的 Playground。
![Xcode 项目导航器中名为 RealmPlayground.playground 的文件的屏幕截图](/zh-cn/docs/atlas/device-sdks/static/dcb7dc94d0cffcd77e92a66c7c4934bd/1fffd/xcode-playground-see-playground-in-project-navigator.webp)
点击放大
导入 Realm
添加以下声明以在 Playground 中使用 Realm:
import RealmSwift
使用 Realm 进行实验
使用 Realm 进行试验。 对于本示例,我们将:
class Drink: Object { var name = "" var rating = 0 var source = "" 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 文件
在 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。