在Swift中,将"anywhere"注册为协议的委托

Fat*_*tie 2 messaging singleton ios swift swift-protocols

我有一个复杂的视图类,

class Snap:UIViewController, UIScrollViewDelegate
   {
   }
Run Code Online (Sandbox Code Playgroud)

最终的结果是,用户可以选择一种颜色......

protocol SnapProtocol:class
    {
    func colorPicked(i:Int)
    }
class Snap:UIViewController, UIScrollViewDelegate
   {
   someDelegate.colorPicked(blah)
   }
Run Code Online (Sandbox Code Playgroud)

那么谁将会处理它.

让我们说你肯定知道响应者链上有什么东西,甚至走过容器视图,这是一个SnapProtocol.如果是这样,您可以使用这个可爱的代码来调用它

var r : UIResponder = self
repeat { r = r.nextResponder()! } while !(r is SnapProtocol)
(r as! SnapProtocol).colorPicked(x)
Run Code Online (Sandbox Code Playgroud)

如果您愿意,可以使用此最佳扩展名

public extension UIResponder        // walk up responder chain
    {
    public func next<T>() -> T?
        {
        guard let responder = self.nextResponder()
            else { return nil }
        return (responder as? T) ?? responder.next()
        }
    }
Run Code Online (Sandbox Code Playgroud)

礼貌SnapProtocol告诉这些家伙并安全地找到你上面的任何人,

 (next() as SnapProtocol?)?.colorPicked(x)
Run Code Online (Sandbox Code Playgroud)

那很棒.

但.如果想要获得它的对象colorPicked是一个骑士 - 离开你,沿着一些复杂的侧链,和/或你甚至不知道哪个对象想要它.

我目前的解决方案就是这个,我有一个单身"游戏经理"式的班级,

public class .. a singleton
    {

    // anyone who wants a SnapProtocol:
    var useSnap:SnapProtocol! = nil

    }
Run Code Online (Sandbox Code Playgroud)

一些怪异的课,无论在哪里,都想吃SnapProtocol ......

class Dinosaur:NSObject, SnapProtocol
    {
    ....
    func colorPicked(index: Int)
        {...}
Run Code Online (Sandbox Code Playgroud)

...因此,要将其设置为所需的委托,请使用单例

 thatSingleton.useSnap = dinosaur
Run Code Online (Sandbox Code Playgroud)

显然,这很好.

另请注意,我可以轻松地在单例中编写一个小系统,以便协议的任意数量的用户可以动态地注册/注销那里并获得调用.

但它有明显的问题,它不是非常"模式",而且似乎是非惯用的暴力.

所以.我真的,在Swift环境中以正确的方式做到这一点吗?

我是否真的让自己感到困惑,在今天的iOS中我应该使用一些完全不同的模式,将这些"消息发送给任何想要它们的人?" ...也许我甚至不应该使用协议?

ric*_*ter 5

"向任何想要他们的人发送消息"几乎都是对他们的描述NSNotificationCenter.

确实,它不是从一开始就为闭包,强类型和面向协议的编程等Swift模式设计的API.(如其他评论/答案所述,如果您真的需要这些功能,开源SwiftNotificationCenter是一个不错的选择.)

然而,它NSNotificationCenter 强大且经过强化的 - 它是数千条消息的基础,这些消息在每次通过运行循环时在数百个对象之间被发送.


这是在Swift中使用NSNotificationCenter的非常简洁的方法:

/sf/answers/1732973301/