我应该使用委托方法还是 UINotificationCenter
Should I use a delegate method or UINotificationCenter
所以现在我有一个 rootViewController
,它有一个 UIPageViewController
作为它唯一的子视图,rootViewController
基本上是 UIPageViewController
的包装器 class。现在我想禁用来自 ViewControllerA
的 UIPageViewController
的滚动(归 rootViewController
所有)。
现在我已经为 rootViewController
实现了一个委托方法(由 ViewControllerA
创建),它告诉 UIPageViewController
它必须根据 [=15] 给出的信息停止滚动=].但是要让 ViewControllerA
能够调用 rootViewController
实现的委托方法,就需要 rootViewController
是 ViewControllerA
的实例变量。
这是最佳做法吗?使用 NSNotificationCenter
会是更好的选择吗?还是这些方法中的 none 是最佳选择?
有很多方法可以解决您的问题。如果您可以设置将 rootViewController 变量添加到您的 ViewControllerA 并能够在创建 ViewControllerA 期间设置它,那么这将是调用它的最快方法。当涉及多个线程时,我通常使用 NSNotificationCenter。因此,如果我有一个异步任务 运行 ,比如 HTTP 调用,它需要应用程序根据结果做出相应的反应,那么使用 NSNotificationCenter 是一个不错的选择,因为它可以轻松地在应用程序范围内发送消息,而你只需要根据消息添加观察者即可。
最佳做法是使用委托或回调 属性:
final class ViewControllerA: UIViewController
{
var callback: (ViewControllerA -> ())?
func somethingHappened()
{
callback?(self)
}
}
如果您使用这种样式,请务必避免引用循环:
let viewControllerA = ViewControllerA()
viewControllerA.callback = { [weak self] _ in ... }
如果您使用委托,请使用 weak var
:
避免引用循环
weak var delegate: ViewControllerADelegate?
这些样式比 NSNotificationCenter
更可取,因为它们类型安全、可读性和灵活性更高。
所以现在我有一个 rootViewController
,它有一个 UIPageViewController
作为它唯一的子视图,rootViewController
基本上是 UIPageViewController
的包装器 class。现在我想禁用来自 ViewControllerA
的 UIPageViewController
的滚动(归 rootViewController
所有)。
现在我已经为 rootViewController
实现了一个委托方法(由 ViewControllerA
创建),它告诉 UIPageViewController
它必须根据 [=15] 给出的信息停止滚动=].但是要让 ViewControllerA
能够调用 rootViewController
实现的委托方法,就需要 rootViewController
是 ViewControllerA
的实例变量。
这是最佳做法吗?使用 NSNotificationCenter
会是更好的选择吗?还是这些方法中的 none 是最佳选择?
有很多方法可以解决您的问题。如果您可以设置将 rootViewController 变量添加到您的 ViewControllerA 并能够在创建 ViewControllerA 期间设置它,那么这将是调用它的最快方法。当涉及多个线程时,我通常使用 NSNotificationCenter。因此,如果我有一个异步任务 运行 ,比如 HTTP 调用,它需要应用程序根据结果做出相应的反应,那么使用 NSNotificationCenter 是一个不错的选择,因为它可以轻松地在应用程序范围内发送消息,而你只需要根据消息添加观察者即可。
最佳做法是使用委托或回调 属性:
final class ViewControllerA: UIViewController
{
var callback: (ViewControllerA -> ())?
func somethingHappened()
{
callback?(self)
}
}
如果您使用这种样式,请务必避免引用循环:
let viewControllerA = ViewControllerA()
viewControllerA.callback = { [weak self] _ in ... }
如果您使用委托,请使用 weak var
:
weak var delegate: ViewControllerADelegate?
这些样式比 NSNotificationCenter
更可取,因为它们类型安全、可读性和灵活性更高。