IOS - 委托(delegate)与通知

标签 ios swift authentication delegates nsnotifications

想听听您对以下架构的看法:

在我的应用程序中,我有一个处理异步登录的静态类 (LoginManager)。一旦登录阶段完成,应用程序应该响应并转换到另一个状态。

我有2个实现建议

  1. 使用委托(delegate):

    import Foundation
    
    protocol LoginManagerDelegate{
        func onLogin(result:AnyObject)
    }
    
    class LoginManager {
        struct Wrapper {
            static var delegate:LoginManagerDelegate?
        }
    
        class func userDidLogin(result){            
             Wrapper.delegate?.onLogin(result)
        }
    
    }
    
  2. 使用通知:

    import Foundation
    
    class LoginManager {
    
        class func userDidLogin(result){            
             NSNotificationCenter.defaultCenter().postNotificationName("onLogin", object: result)
        }
    
    }
    

:最好的方法是什么?

最佳答案

为了

  1. 委托(delegate)/协议(protocol)

当你想从当前 View Controller 更新或完成你以前的 Controller 中的任何过程时,通常使用它。所以如果你想更新以前的 View Controller 中的值,那么委托(delegate)/协议(protocol)是更可取的。

所以基本上是一对一的关系。

  1. 通知

当您想从任何其他 View Controller 更新 View Controller 中的值时,通常会使用它。所以它基本上是一对多的关系。

因此请根据您的要求使用此类型。

也许这对你有帮助。

关于IOS - 委托(delegate)与通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27647047/

相关文章:

IOS 关闭应用程序时丢失 FBSession

ios - 如何通过 qml 在移动设备中创建新窗口?

ios - 使用 Swift 编译静态库时出错 "unknown option character ` X' in : -Xlinker"

swift - 如何计算在 iOS 的 CollectionView 中调用 indexpath 的次数?

ios - 使用 scrollViewDidScroll 移动 ChildViewController 的 subview

ios - 如何在越狱的 iOS 设备上截取整个屏幕?

ios - 单元格的详细 TextView 未显示?

authentication - Asp.net core 2 - Web Api 中的外部身份验证

php认证/数据库代码风格

ios - FirebaseAuth UI Google SignIn 在 iOS 上启用 cookie