A delegate
设计模式在您想要将数据传递回呈现的UIViewController
时非常有用,正如您在问题中指出的那样。如果你不想去委托设计模式,那么也许你可以使用NSNotificationCenter
?它没有太多的内存,它触发了一个应用程序范围的广播,可以通过一个NSObserver获取,您可以将它放在您的演示文稿UIViewController
(即假设您的演示UIViewController
仍在内存中)。例如,代码可以看起来像沿此线的东西:
ViewControllerA.swift
override func viewDidLoad(){
super.viewDidLoad()
let notifCenter = NSNotificationCenter.defaultCenter()
notifCenter.addObserver(self, selector: #selector(ViewControllerA.methodToTrigger), name: "pickedRestaurantNoti", object: nil)
}
func methodToTrigger(notification:NSNotification){
let userInfo:Dictionary<String,String!> = notification.userInfo as Dictionary<String,String!>
let pickedRestaurantFromB = userInfo["pickedRestaurant"]
// pickedRestaurantFromB should have the value of "Restaurant 1"
// handle that value now that you have gotten it
}
ViewControllerB.swift
func someMethod(){
let notifCenter = NSNotificationCenter.defaultCenter()
notifCenter.postNotificationName("pickedRestaurantNoti",
object:nil,
userInfo:["pickedRestaurant":"Restaurant 1"])
}
你是什么意思委托模式是“非一般”?这正是该模式设计的目的,以确保呈现的视图控制器仅关注其自己的实现;代表可以根据需要回应回调,而不会影响子控制器的责任。 – Stuart
那么,@Stuart我的意思是我需要多次实现相同的代码。但是在做了一些扩展研究之后,我同意这对我来说是最好的选择。 – user4992124