문서 메뉴
문서 홈
/ /
Atlas Device SDK
/ /

변경 사항에 React - Swift SDK

이 페이지의 내용

  • 객체 관찰
  • 쿼리 결과 관찰
  • 관찰 결과 정렬
  • 섹션별 결과 관찰
  • 앱 상태 관찰

The Swift SDK provides the @ObservedRealmObject property wrapper that invalidates a view when an observed object changes. You can use this property wrapper to create a view that automatically updates itself when the observed object changes.

struct DogDetailView: View {
@ObservedRealmObject var dog: Dog
var body: some View {
VStack {
Text(dog.name)
.font(.title2)
Text("\(dog.name) is a \(dog.breed)")
AsyncImage(url: dog.profileImageUrl) { image in
image.resizable()
} placeholder: {
ProgressView()
}
.aspectRatio(contentMode: .fit)
.frame(width: 150, height: 150)
Text("Favorite toy: \(dog.favoriteToy)")
}
}
}

Swift SDK는 쿼리 결과 컬렉션을 관찰할 수 있는 @ObservedResults 속성 래퍼를 제공합니다. ObservedResults 컬렉션에 빠르게 쓰기를 수행할 수 있으며, 관찰된 쿼리가 변경되면 뷰가 자동으로 업데이트됩니다. 예를 들어 onDelete 를 사용하여 관찰된 개 목록에서 개를 제거할 수 있습니다.

참고

@ObservedResults 속성 래퍼는 SwiftUI 보기에서 사용하기 위한 것입니다. View 모델에서 결과를 관찰하려면 변경 리스너를 등록하십시오.

struct DogsView: View {
@ObservedResults(Dog.self) var dogs
/// The button to be displayed on the top left.
var leadingBarButton: AnyView?
var body: some View {
NavigationView {
VStack {
// The list shows the dogs in the realm.
// The ``@ObservedResults`` above implicitly opens a realm and retrieves
// all the Dog objects. We can then pass those objects to views further down the
// hierarchy.
List {
ForEach(dogs) { dog in
DogRow(dog: dog)
}.onDelete(perform: $dogs.remove)
}.listStyle(GroupedListStyle())
.navigationBarTitle("Dogs", displayMode: .large)
.navigationBarBackButtonHidden(true)
.navigationBarItems(
leading: self.leadingBarButton,
// Edit button on the right to enable rearranging items
trailing: EditButton())
}.padding()
}
}
}

다음도 참조하세요.

Realm에서 지원하는 쿼리 구문 및 쿼리 유형에 대한 자세한 내용은 다음을 참조하세요: 읽기 - Swift SDK데이터 필터링 - Swift SDK를참조하세요.

@ObservedResults 속성 래퍼는 SortDescriptor 매개 변수를 사용하여 쿼리 결과를 정렬할 수 있습니다.

struct SortedDogsView: View {
@ObservedResults(Dog.self,
sortDescriptor: SortDescriptor(keyPath: "name",
ascending: true)) var dogs
var body: some View {
NavigationView {
// The list shows the dogs in the realm, sorted by name
List(dogs) { dog in
DogRow(dog: dog)
}
}
}
}

계산된 속성을 @ObservedResults에 대한 SortDescriptor 으로 사용할 수 없습니다.

버전 10.29.0의 새로운 기능

객체의 속성에서 생성된 키에 의해 섹션으로 구분된 결과 집합을 관찰할 수 있습니다. 보관되지 않는 모델에 계산된 변수를 추가했으며, 이는 결과 집합을 섹션으로 구분하는 데에만 사용됩니다.

var firstLetter: String {
guard let char = name.first else {
return ""
}
return String(char)
}

그런 다음 @ObservedSectionedResults 속성 래퍼(wrapper)를 사용하여 계산된 변수 키를 기준으로 섹션으로 나뉜 결과 집합을 관찰할 수 있습니다.

@ObservedSectionedResults(Dog.self,
sectionKeyPath: \.firstLetter) var dogs

관찰된 섹션별 결과를 사용하여 섹션별로 구분된 List 보기를 채울 수 있습니다.

struct SectionedDogsView: View {
@ObservedSectionedResults(Dog.self,
sectionKeyPath: \.firstLetter) var dogs
/// The button to be displayed on the top left.
var leadingBarButton: AnyView?
var body: some View {
NavigationView {
VStack {
// The list shows the dogs in the realm, split into sections according to the keypath.
List {
ForEach(dogs) { section in
Section(header: Text(section.key)) {
ForEach(section) { dog in
DogRow(dog: dog)
}
}
}
}
.listStyle(GroupedListStyle())
.navigationBarTitle("Dogs", displayMode: .large)
.navigationBarBackButtonHidden(true)
.navigationBarItems(
leading: self.leadingBarButton,
// Edit button on the right to enable rearranging items
trailing: EditButton())
}.padding()
}
}
}

앱에서 Atlas Device Sync를 사용하는 경우 객체가 로그인 상태 변경에 반응하는 것을 관찰할 수 있습니다. 이렇게 하면 앱이 app.currentUser 있는 동안 작업을 수행하거나 app.currentUser 없는 경우 사용자에게 로그인하도록 지시할 수 있습니다.

Realm은 사용자 자격 증명을 기기에 캐싱하기 때문에 app.currentUser 파일이 있는 동안에는 앱이 오프라인으로 작동할 수 있습니다.

/// This view observes the Realm app object.
/// Either direct the user to login, or open a realm
/// with a logged-in user.
struct FlexibleSyncContentView: View {
// Observe the Realm app object in order to react to login state changes.
@ObservedObject var app: RealmSwift.App
var body: some View {
if let user = app.currentUser {
// Create a `flexibleSyncConfiguration` with `initialSubscriptions`.
// We'll inject this configuration as an environment value to use when opening the realm
// in the next view, and the realm will open with these initial subscriptions.
let config = user.flexibleSyncConfiguration(initialSubscriptions: { subs in
let peopleSubscriptionExists = subs.first(named: "people")
let dogSubscriptionExists = subs.first(named: "dogs")
// Check whether the subscription already exists. Adding it more
// than once causes an error.
if (peopleSubscriptionExists != nil) && (dogSubscriptionExists != nil) {
// Existing subscriptions found - do nothing
return
} else {
// Add queries for any objects you want to use in the app
// Linked objects do not automatically get queried, so you
// must explicitly query for all linked objects you want to include.
subs.append(QuerySubscription<Person>(name: "people"))
subs.append(QuerySubscription<Dog>(name: "dogs"))
}
})
OpenFlexibleSyncRealmView()
.environment(\.realmConfiguration, config)
} else {
// If there is no user logged in, show the login view.
LoginView()
}
}
}

돌아가기

Realm 구성 및 열기

다음

뷰 간에 Realm 데이터 전달