iTi*_*ink 4 singleton delegates protocols ios swift
如何使用singleton/shared类的委托方法?有一个单例类定义了一些协议,但我没有得到如何访问其他类中的委托函数.
参考代码片段(swift):
Run Code Online (Sandbox Code Playgroud)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() } }
这个实现是否正确?
首先,我想指出:
1-创建单例类应包含:
private init() {}
Run Code Online (Sandbox Code Playgroud)
这导致仅通过使用其共享实例来强制访问类.
2-正如Max的答案中所提到的,委托应该是可选的,并且具有弱引用.
3-协议应该是一种类,如下所示:
protocol AClassDelegate: class
Run Code Online (Sandbox Code Playgroud)
有关详细信息,您可能需要查看此问答.
现在,让我们假设-用于测试目的订立的是,method1()从AClassDelegate应调用时被调用foo()的A类:
protocol AClassDelegate: class {
func method1()
}
class A {
private init() {}
static let shared = A()
weak var delegate: AClassDelegate?
func foo() {
print(#function)
delegate?.method1()
}
}
Run Code Online (Sandbox Code Playgroud)
让我们实现符合以下条件的类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")
}
}
Run Code Online (Sandbox Code Playgroud)
输出应该是:
let b = B()
b.bar()
// this will print:
/*
foo()
calling the delegate method B Class
*/
let c = C()
c.bar()
// this will print:
/*
foo()
calling the delegate method C Class
*/
Run Code Online (Sandbox Code Playgroud)
这几乎是正确的。你没有考虑到单身人士永远存在(除非你在某处销毁它),但它的委托可能不会。所以为了避免崩溃,将该delegate属性设置为weak和可选的。
weak var delegate: AClassDelegate?
Run Code Online (Sandbox Code Playgroud)
这样你就不必关心委托是否存在。
| 归档时间: |
|
| 查看次数: |
3251 次 |
| 最近记录: |