【问题标题】:How to get access to ViewController's property from AppDelegate if it is in TabBarController?如果它在 TabBarController 中,如何从 AppDelegate 访问 ViewController 的属性?
【发布时间】:2019-03-17 04:02:15
【问题描述】:

我有一个 UITabBarController 作为根视图控制器,我需要访问 ProfileViewController 中的一个属性。

这是故事板:

func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
    let rootVC = self.window?.rootViewController

    if "com.spbpu.csse" == url.scheme {
        //I need here to get VC property and do something like vc.oauth2.handleRedirectURL(url)

        return true
    }
    return false
}

【问题讨论】:

    标签: ios swift uitabbarcontroller appdelegate


    【解决方案1】:

    我建议不要从应用委托访问视图控制器。它在应用程序委托中放置了太多关于视图控制器需要(及其结构)的知识。这是一个脆弱的设计。

    更好的方法是定义您自己的NotificationCenter 通知。使用所需的有效负载(URL)从应用代理发布该通知。

    在适当的视图控制器中添加代码以侦听该自定义通知。当视图控制器收到通知时,获取 URL 并采取相应措施。

    这种方法将谁关心通知以及如何处理通知的知识放在它所属的位置。它还允许多个视图控制器(或其他类)对同一个通知进行操作,而无需在应用程序委托中添加越来越多的逻辑。

    【讨论】:

    • 在我的 ProfileViewController 我添加了 NotificationCenter.default.addObserver(self, selector: #selector(self.handleRedirect(notification:)), name: NSNotification.Name(rawValue: OAuth2AppDidReceiveCallbackNotification), object: nil)@objc func handleRedirect(notification: NSNotification) { oauth2.handleRedirectURL(notification.object as! URL) } 所以在 AppDelegate 中只是 NotificationCenter.default.post(name: NSNotification.Name(rawValue: OAuth2AppDidReceiveCallbackNotification), object: url)
    【解决方案2】:

    找到欲望视图控制器的最简单方法:

    let profile = (rootVC as? UITabBarController)?.viewControllers?
        .first { $0 is ProfileViewController }
        .map { $0 as! ProfileViewController } // this unwrap is safe since we filtered by first
    profile?.doSomething()
    

    更干净的方法是:

    • 有某种OAuthService 负责OAuth 身份验证、令牌等
    • appDelegate 对OAuthService 有很强的引用,因为很可能在applicationDidFinishLaunching(_) 中创建它。
    • OAuthService 提供委托/通知/状态流以通知会话状态更改
    • ProfileViewConctoller 订阅了此更改

    【讨论】:

      【解决方案3】:

      正确的方法应该是拥有一个“dataSource”/“DBManager”,您可以调用它,它会向每个请求对象发送数据。

      (我通常是单身人士..即使单身人士经常被劝阻..:))

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-18
        • 2020-06-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多