ios - 从 VC 返回数据而不丢失范围的正确方法

标签 ios swift delegation completionhandler

我已经解决了我的问题,但我不知道是否有更好的方法。我正在制作锻炼日志。我想从 VC1 选择一个日期并按下 VC 2 选择一项练习,然后将练习返回到 VC1。我正在使用这样的委托(delegate)来获取返回的数据。

VC1

//Here the date of the new Workout. I have to get the exercise first.
func addButtonInSectionDidClick(date:NSDate) {

   //Delegate will call exerciseSelectionDismissedWithExerciseName        
   exerciseSelectionWireframe!.dismissDelegate = self 

   //Push the VC 2 for exercise selection
   exerciseSelectionWireframe!.presentExerciseSelection()                   

 }

func  exerciseSelectionDismissedWithExerciseName(name:String) {

        //Returned but I can't use the var date anymore.


    }

有问题。我无法在委托(delegate)方法中使用 var date,但我需要这样做。

我的解决方法是使用完成 block 作为私有(private)变量。

    private var completionBlock: (() -> Void)?

    //Here the date of the new Workout. I have to get the exercise first.
    func addButtonInSectionDidClick(date:NSDate) {

       //Delegate will call exerciseSelectionDismissedWithExerciseName        
       exerciseSelectionWireframe!.dismissDelegate = self 

       //Push the VC 2 for exercise selection
       exerciseSelectionWireframe!.presentExerciseSelection() 

       completionBlock = {        
          var myDate = date   
      }               

 }

    func  exerciseSelectionDismissedWithExerciseName(name:String) {

        if let completionBlock = completionBlock {
                     completionBlock()     
        }

    }

还有其他预定义的方法可以做到这一点吗?我不喜欢那里有completionBlock var。

最佳答案

使用共享首选项或使用单例,例如:

import Foundation
class ConstantData {
var myDate:NSDate    = NSDate()
}

let sharedDateAccess = ConstantData()

因此您可以更改变量值,并且可以从任何地方访问它:

func addButtonInSectionDidClick(日期:NSDate) {

   //Delegate will call exerciseSelectionDismissedWithExerciseName        
   exerciseSelectionWireframe!.dismissDelegate = self 

   //Push the VC 2 for exercise selection
   exerciseSelectionWireframe!.presentExerciseSelection() 

   sharedDataAccess.myDate = date   

 }

关于ios - 从 VC 返回数据而不丢失范围的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31761275/

相关文章:

xcode - 如何初始化相互依赖的属性

python - 在 Python 3 中创建自动委托(delegate)包装类

objective-c - 子类化后的委托(delegate)?

具有方法参数值或使用委托(delegate)的 c# 函数

ios - Swift 3 不安全指针

ios - 如何在 iPhone 中播放 Youtube 视频

ios - AVSpeechSynthesisVoice 未正确加载

ios - 如果用户向上滚动控制中心,如何从 iOS 键盘扩展检测到?

ios - 处理 Firebase childDeleted 和 childModified 观察者 Swift

ios : How to get photo url which is deleted in photo. 应用程序