如何使用单例/共享类的委托方法?
有一个单例类定义了一些协议,但我不知道如何访问其他类中的委托函数。
供参考的代码片段(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()
}
}
这个实现正确吗?
首先,我想指出:
1-创建单例类应包含:
private init() {}
这导致强制只能通过使用其共享实例来访问该类。
2-正如中提到的麦克斯的回答 https://stackoverflow.com/a/42976838/5501940,委托应该是可选的并且有一个weak参考。
3-该协议应该是一种class, 如下:
protocol AClassDelegate: class
有关更多信息,您可能需要检查此.
现在,为了测试目的,我们假设method1()
from AClassDelegate
打电话时应该被叫到foo()
from A
class:
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")
}
}
Output应该:
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
*/
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)