在不丢失范围的情况下从VC返回数据的正确方法

时间:2015-08-01 11:24:11

标签: ios swift delegation completionhandler

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

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.


    }

有问题。我不能在委托方法中使用var日期,但我需要。

我的解决方法是使用完成块作为私有var。

    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。

1 个答案:

答案 0 :(得分:0)

使用分享偏好或使用单身,例如:

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

let sharedDateAccess = ConstantData()

所以你可以改变变量值,你可以从任何地方访问它:

func addButtonInSectionDidClick(date:NSDate){

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

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

   sharedDataAccess.myDate = date   

 }