为什么 @Published 在 NSManagedObject 中不起作用?
Why does @Published not work in NSManagedObject?
@Published
在 ObservableObject
中使用时可以正确发布。但在NSManagedObject
(符合ObservableObject
)中使用时似乎不会发布。
在以下示例中,当使用 Data1
时,选择器下方的文本会更新。但是使用 Data2
它不是。这是为什么?
import SwiftUI
import CoreData
class Data1: ObservableObject {
@Published var direction: Direction = .left
}
class Data2: NSManagedObject { // NSManagedObject conforms to ObservableObject
@Published var direction: Direction = .left
}
enum Direction {
case left
case right
}
@main
struct SwiftUITestApp: App {
var body: some Scene {
WindowGroup {
ContentView().environmentObject(Data2()) // Or Data1() as needed
}
}
}
struct ContentView: View {
@EnvironmentObject private var data: Data2
var body: some View {
VStack {
Picker("", selection: $data.direction) {
Text("Left").tag(Direction.left)
Text("Right").tag(Direction.right)
}.pickerStyle(.wheel)
switch data.direction {
case .left:
Text("Selected: Left")
case .right:
Text("Selected: Right")
}
}.padding()
}
}
解决方案是添加一个瞬态核心数据属性。瞬态属性已发布但未持久化。
或者,您可以像这样发布更改:
class Data2: NSManagedObject {
@Published var direction: Direction = .left { // @Published is optional
willSet {
objectWillChange.send()
}
}
}
@Published
在 ObservableObject
中使用时可以正确发布。但在NSManagedObject
(符合ObservableObject
)中使用时似乎不会发布。
在以下示例中,当使用 Data1
时,选择器下方的文本会更新。但是使用 Data2
它不是。这是为什么?
import SwiftUI
import CoreData
class Data1: ObservableObject {
@Published var direction: Direction = .left
}
class Data2: NSManagedObject { // NSManagedObject conforms to ObservableObject
@Published var direction: Direction = .left
}
enum Direction {
case left
case right
}
@main
struct SwiftUITestApp: App {
var body: some Scene {
WindowGroup {
ContentView().environmentObject(Data2()) // Or Data1() as needed
}
}
}
struct ContentView: View {
@EnvironmentObject private var data: Data2
var body: some View {
VStack {
Picker("", selection: $data.direction) {
Text("Left").tag(Direction.left)
Text("Right").tag(Direction.right)
}.pickerStyle(.wheel)
switch data.direction {
case .left:
Text("Selected: Left")
case .right:
Text("Selected: Right")
}
}.padding()
}
}
解决方案是添加一个瞬态核心数据属性。瞬态属性已发布但未持久化。
或者,您可以像这样发布更改:
class Data2: NSManagedObject {
@Published var direction: Direction = .left { // @Published is optional
willSet {
objectWillChange.send()
}
}
}