在swift中,如何在类和视图之间保持对象的活力



我有一个名为AudioRecorder的类和一个名为RecorderView的视图。Audiorecorder具有以下功能

  • 启动录制()-->开始录制并获取录制开始时间
  • 停止录制()-->停止录制并获取录制停止时间
  • saveToCoreData()-->将startTime、stopTime和评级保存到核心数据

它的工作原理是,RecorderView允许用户通过调用AudioRecorder中的函数来启动和停止录制。一旦用户停止录制,就会显示一个名为RatingView的新视图。用户在RatingView中提供评级并点击提交。通过选择提交,RecorderView中的saveToCoreData将使用用户提供的评级进行调用。这里的问题是,当视图调用saveToCoreData时,startTimestopTime丢失了。这就是为什么他们是";nil";并且只有CCD_ 13具有适当的值。如何使startTimestopTime保持活动状态以备下次使用?有办法解决这个问题吗?

import SwiftUI
struct RecorderView: View {
@ObservedObject var audioRecorder: AudioRecorder
@State private var showRatingView = false

var body: some View {
VStack {
if audioRecorder.recording == false {
Button(action: {self.audioRecorder.startRecording()}) {
Image(systemName: "circle.fill")
}
} else {
Button(action: {self.audioRecorder.stopRecording(); showRatingView = true}) {
Image(systemName: "stop.fill")
}
}
VStack {
if showRatingView == true {
NavigationLink(destination: SurveyRatingView(rating: 1, audioRecorder: AudioRecorder()), isActive: self.$showRatingView) { EmptyView()}
}
}
}
}
}

struct RatingView: View {

@Environment(.managedObjectContext) var moc
@State var rating: Int16
@ObservedObject var audioRecorder: AudioRecorder

@State private var displayNewView: Bool = false

var body: some View {
VStack {

Text("How was the recording experience?")
//          RatingView(rating: $survey)
Button(action: {
self.audioRecorder.saveToCoreData(rating: rating)
}) {
Text("Submit Response")
}
}
.navigationBarBackButtonHidden(true)
}
}

这就是类AudioRecorder

class AudioRecorder:  NSObject, ObservableObject {
@Published var startTime: Date
@Published var stopTime: Date

func startRecording() -> Date {
self.startTime = Date()
//Start recording related code here
}

func stopRecording() -> Date{
// Stop recording related code here
self.stopTime = Date()
}


func saveToCoreData(rating: Int16){
let aRec = AudioRec(context: moc)
aRec.uuid = UUID()
aRec.startTime = self.startTime //This is nil
aRec.stopTime = self.stopTime  //This is nil
aRec.rating = rating  //Only this has a proper value

try moc.save()
}
}

在您的"showRatingView;VStack您正在传递AudioRecorder的一个新实例。您应该传递您已经拥有的实例:

VStack {
if showRatingView == true {
NavigationLink(destination: SurveyRatingView(rating: 1, audioRecorder: self.audioRecorder), isActive: self.$showRatingView) { EmptyView()}
}
}

最新更新