Swift

时间:2017-03-23 12:57:16

标签: ios swift delegates singleton protocols

如何使用singleton / shared类的委托方法? 有一个单例类定义了一些协议,但我没有得到如何访问其他类中的委托函数。

参考代码片段(swift):

protocol AClassDelegate
{
  func method1()
}

class A
{
   static let shared = A()

   override init() {
     //initialisation of member variables
   }

   var delegate: AClassDelegate
   func foo() {

   }
}


class B: AClassDelegate
{
   func bar() {
      // Note: not getting call to 'foo' method of class 'A'
      A.shared.delegate = self
      A.shared.foo()
   }
}

此实施是否正确?

2 个答案:

答案 0 :(得分:6)

首先,我想指出:

1 - 创建单例类应该包含:

private init() {}

这导致仅通过使用其共享实例来强制访问该类。

2 - 正如Max's Answer中所述,委托应该是可选的,并且有引用。

3 - 协议应该是一种,如下所示:

protocol AClassDelegate: class

有关详细信息,您可能需要查看此Q&A

现在,我们假设 - 出于测试目的 - 从method1()类调用AClassDelegate时应调用来自foo()的{​​{1}}:

A

让我们实现符合protocol AClassDelegate: class { func method1() } class A { private init() {} static let shared = A() weak var delegate: AClassDelegate? func foo() { print(#function) delegate?.method1() } } 的类:

AClassDelegate

输出应为:

class B: AClassDelegate {
    func bar() {
        A.shared.delegate = self
        A.shared.foo()
    }

    func method1() {
        print("calling the delegate method B Class")
    }
}

class C: AClassDelegate {
    func bar() {
        A.shared.delegate = self
        A.shared.foo()
    }

    func method1() {
        print("calling the delegate method C Class")
    }
}

答案 1 :(得分:4)

这几乎是正确的。你没有考虑到单身人士永远存在(除非你在某处摧毁它),但它的代表可能没有。因此,为了避免崩溃,请将delegate属性设置为weak并将其设置为可选。

weak var delegate: AClassDelegate?

这样你就不应该关心委托是否存在。