Usage
down load realm
Realm 官网
Realm库 github.com/realm/realm…
配置 或 Cocoapods
-
1.将Realm.framework从ios/static/文件夹拖曳到您Xcode项目中的文件导航器当中, 确保Copy items if needed选中然后单击Finish
-
2.在Xcode文件导航器中选择您的项目,然后选择您的应用目标,进入到Build Phases选项卡中。在Link Binary with Libraries中单击 + 号然后添加libc++.tbd以及libz.tbd
-
import RealmSwift (导入)
定义对象模型
class Todo: Object {
@Persisted(primaryKey: true) var _id: ObjectId
@Persisted var name: String = ""
@Persisted var status: String = ""
@Persisted var ownerId: String
convenience init(name: String, ownerId: String) {
self.init()
self.name = name
self.ownerId = ownerId
}
}
- 创建
// Open the local-only default realm
let realm = try! Realm()
- 添加
let todo = Todo(name: "Do laundry", ownerId: user.id)
try! realm.write {
realm.add(todo)
}
- 读取
// Get all todos in the realm
let todos = realm.objects(Todo.self)
let todosInProgress = todos.where {
$0.status == "InProgress"
}
print("A list of all todos in progress: \(todosInProgress)")
- 修改
// All modifications to a realm must happen in a write block.
let todoToUpdate = todos[0]
try! realm.write {
todoToUpdate.status = "InProgress"
}
- 删除
// All modifications to a realm must happen in a write block.
let todoToDelete = todos[0]
try! realm.write {
// Delete the Todo.
realm.delete(todoToDelete)
}
- 添加观察
// Retain notificationToken as long as you want to observe
let notificationToken = todos.observe { (changes) in
switch changes {
case .initial: break
// Results are now populated and can be accessed without blocking the UI
case .update(_, let deletions, let insertions, let modifications):
// Query results have changed.
print("Deleted indices: ", deletions)
print("Inserted indices: ", insertions)
print("Modified modifications: ", modifications)
case .error(let error):
// An error occurred while opening the Realm file on the background worker thread
fatalError("\(error)")
}
}
- SwiftUI中 注入上下文
ContentView()
.environment(\.realmConfiguration, Realm.Configuration( /* ... */ ))
Realm是由美国YCombinator孵化的创业团队历时几年打造,第一个专门针对移动平台设计的数据库 Realm是一个跨平台的移动数据库引擎,目前支持iOS、Android平台,同时支持Objective-C、Swift、Java、React Native、Xamarin等多种编程语言 Realm并不是对SQLite或者CoreData的简单封装, 是由核心数据引擎C++打造,是拥有独立的数据库存储引擎,可以方便、高效的完成数据库的各种操作
Realm的优势与亮点 -> 开源。Realm移动端数据库相关代码已全部开源。数千开发者在GitHub上参与了相关工作。另外还有几百个Realm数据库相关的扩展。简单易用:Core Data、SQLite庞大的学习量和繁杂的代码足以吓退绝大多数刚入门的开发者,而换用Realm,则可以极大地减少学习代价和学习时间,让应用及早用上数据存储功能。 跨平台:现在绝大多数的应用开发并不仅仅只在iOS平台上进行开发,还要兼顾到Android平台的开发。为两个平台设计不同的数据库是不明智的,而使用Realm数据库,iOS和Android无需考虑内部数据的架构,调用Realm提供的API就可以完成数据的交换 线程安全。程序员无需对在不同线程中,对数据库的读取一致性做任何考虑,Realm会保证每次读取都得到一致的数据
可视化工具Realm Browser (In AppStore)