SWIFT:将数据从一个类传递到另一个类

时间:2015-08-16 18:04:14

标签: swift segue uistoryboardsegue

所以我一直在使用prepareForSegue将数据从一个变量传递到另一个类。当我传递数据的变量与destinationViewController一起使用时,一切正常。但是当它不是时会发生什么?

示例:我正在从ViewController1移动到ViewController2,但我希望ViewController1中的数据转到"非ViewController"即使我仍然希望segue到VC2发生。

有什么想法吗?谢谢!

 override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if (segue.identifier == "stopRecording") {
            //let playSoundsVC:PlaySoundsViewController = segue.destinationViewController as! PlaySoundsViewController
            let audioEffectsClass = AudioEffect()
            let data = sender as! RecordedAudio
            audioEffectsClass.receivedAudio = data
        }
    }

导入基金会 导入AVFoundation

class AudioEffect {

let session = AVAudioSession.sharedInstance()
var audioEngine: AVAudioEngine!
var audioPlayerNode: AVAudioPlayerNode!
var audioFile: AVAudioFile!
var receivedAudio: RecordedAudio!
var changeEffect = AVAudioUnitTimePitch()


func create(){
    //output is through speakers

    do{
        try session.overrideOutputAudioPort(AVAudioSessionPortOverride.Speaker)
    } catch {print("Failed output audio through speakers.")}

    audioEngine = AVAudioEngine()

    audioPlayerNode = AVAudioPlayerNode()
    audioEngine.attachNode(audioPlayerNode)


}

func playAudio(){
    audioEngine.stop()
    audioEngine.reset()
    do {
        audioFile = try AVAudioFile(forReading: receivedAudio.filePathUrl)
    } catch {print("Failed to create file.")}

    audioPlayerNode.scheduleFile(audioFile, atTime: nil, completionHandler: nil)
    do {
        try audioEngine.start()
    } catch {}
    audioPlayerNode.play()

    audioEngine.attachNode(changeEffect)
    audioEngine.connect(audioPlayerNode, to: changeEffect, format: nil)
    audioEngine.connect(changeEffect, to: audioEngine.outputNode, format: nil)
}

func playAudioWithVariablePitch(pitch:Float) {
    changeEffect.pitch = pitch
    create()
    playAudio()
}

func playAudioWithVariableRate(rate: Float){
    changeEffect.rate = rate
    create()
    playAudio()

}

func stopAudio(){
    audioEngine.stop()
}

}

2 个答案:

答案 0 :(得分:0)

如果您有一个引用该类的变量,请创建一个方法来接收该类中的数据并调用该方法并在prepareForSegue中传递数据。

答案 1 :(得分:0)

嗯,我希望我理解你的权利......但如果我理解你,我不知道应该是什么问题?!?如果您将数据传递给子类UIViewcontroller类,或者传递给任何其他类,它只是相同的?!? : - )

你得到什么错误?或者如果您运行代码会发生什么?

也许这有助于你?

class VCOne: UIViewController {

    lazy var audioEffect: AudioEffect = AudioEffect()

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if (segue.identifier == "stopRecording") {
            if let recordedAudio: RecordedAudio = sender as? RecordedAudio {
                audioEffect.receivedAudio = recordedAudio
            }
        }
    }

}

class AudioEffect {
    var receivedAudio: RecordedAudio?
}