我已经解决了我的问题,但我不知道是否有更好的方法。我正在制作锻炼日志。我想从 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/