You may have already known how to using Realm with Swift. In case you were not, we would like to have a quick review.
Realm With Swift
Model
import Foundation
import RealmSwift
class Item:Object, ObjectKeyIdentifiable {
@Persisted(primaryKey: true) var _id: ObjectId
@Persisted var title = ""
@Persisted(originProperty: "items") var group: LinkingObjects<Group>
}
class Group:Object, ObjectKeyIdentifiable {
@Persisted(primaryKey: true) var _id: ObjectId
@Persisted var items = RealmSwift.List<Item>()
}
Get Results
let realm = try! Realm()
let groups = realm.objects(Group.self)
Mutating Data
try! realm.write {
let group = Group()
realm.add(group, update: .all)
group.items.append(Item())
}
Realm With SwiftUI
Model in Realm with SwiftUI is the same. However, how to getting results and mutating data are much different.
Get Results
Results are got implicitly.
import SwiftUI
import RealmSwift
struct ContentView: View {
@ObservedResults(Group.self) var groups
var body: some View {
if let group = groups.last {
MainSwiftUIView(group: group)
} else {
ProgressView().onAppear(perform: {
$groups.append(Group())
})
}
}
}
You can think
@ObservedResultsas some kind ofBindingstruct, its wrappedValue is the original Realm results.
public var wrappedValue: RealmSwift.Results<ResultType> { get }
When you call @ObservedResults(Group.self) var groups, Realm automatically created implicitly.
public init(_ type: ResultType.Type, configuration: RealmSwift.Realm.Configuration? = nil, filter: NSPredicate? = nil, keyPaths: [String]? = nil, sortDescriptor: RealmSwift.SortDescriptor? = nil)
Mutating Data
@ObservedResults(Group.self) var groups
The variable groups and $groups are different. groups is a frozen object of Group. While $groups is a ObservedResults object, it is unfrozen and is used to do mutation.
Frozen object mean the state of the object is unchanged, the normal Realm object is live and unfrozen.
private func add() {
$group.items.append(Item())
}
@ObservedRealmObject
@ObservedRealmObject is similar like @ObservedResults, but it is not results, but for single realm object.
You should take care of the spelling. As there are a lot similar spellings. Like
@ObservableObject,@ObservedObject, they all look like@ObservedRealmObject, if you misspell them, the compiler won't notify and you app won't work.
Also, there are two common naming space issues.RealmSwift.List<T>andSwiftUI.App.