SwiftUI NSManagedObject更改不会更新视图
在我的视图模型中,如果我更新NSManagedObject属性,那么视图将不再更新。我已经附上了代码和视图模型 我在打断视图更新的行前面添加了一条注释SwiftUI NSManagedObject更改不会更新视图,swift,core-data,swiftui,Swift,Core Data,Swiftui,在我的视图模型中,如果我更新NSManagedObject属性,那么视图将不再更新。我已经附上了代码和视图模型 我在打断视图更新的行前面添加了一条注释 class StudySessionCounterViewModel: ObservableObject { fileprivate var studySession: StudySession init(_ studySession: StudySession) { self.studySession = s
class StudySessionCounterViewModel: ObservableObject {
fileprivate var studySession: StudySession
init(_ studySession: StudySession) {
self.studySession = studySession
}
@Published var elapsedTime = 14 * 60
@Published var circleProgress: Double = 0
var timer: Timer?
var formattedTime: String {
get {
let timeToFormat = (Int(studySession.studyTime) * 60) - elapsedTime
let minutes = timeToFormat / 60 % 60
let seconds = timeToFormat % 60
return String(format:"%02i:%02i", minutes, seconds)
}
}
func startTimer() {
self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.timerTicked), userInfo: nil, repeats: true)
studySession.isActive = true //Adding this stops my view from updating
}
@objc func timerTicked() {
elapsedTime += 1
circleProgress = (Double(elapsedTime) / Double(studySession.studyTime * 60))
}
func stop() {
timer?.invalidate()
}
}
这是使用该视图模型的视图。添加该行时,表示格式化时间的文本不再更改,进度循环的进度保持不变。
如果我删除该行,所有内容都会更新并按预期工作
struct StudySessionCounterView: View {
@Environment(\.presentationMode) var presentationMode
@ObservedObject var studySessionCounterVM: StudySessionCounterViewModel
var studySession: StudySession
init(_ studySession: StudySession) {
studySessionCounterVM = StudySessionCounterViewModel(studySession)
self.studySession = studySession
}
@State var showAlert = false
@State var isCounting = false
var body: some View {
VStack {
ZStack {
Text(studySessionCounterVM.formattedTime)
.font(.largeTitle)
ProgressRingView(size: .large, progress: $studySessionCounterVM.circleProgress)
}
Spacer()
if isCounting {
Button(action: {
self.studySessionCounterVM.stop()
self.isCounting = false
}) {
Image(systemName: "stop.circle")
.resizable()
.frame(width: 64, height: 64, alignment: .center)
.foregroundColor(.orange)
}
} else {
Button(action: {
self.studySessionCounterVM.startTimer()
self.isCounting = true
}) {
Image(systemName: "play.circle")
.resizable()
.frame(width: 64, height: 64, alignment: .center)
.foregroundColor(.orange)
}
}
}.padding()
.navigationBarTitle("Matematica", displayMode: .inline)
}
}
更新:发现每次NSManagedObject更改属性时,视图模型都会重新初始化。仍然没有解决方案,不幸的是您找到解决方案了吗?有同样的问题。。。