Swift中的单例类的委托 [英] Delegation of singleton class in Swift
问题描述
如何使用单例/共享类的委托方法?
有一个单例类,其中定义了一些协议,但是我没有获得如何访问其他类中的委托函数的方法。
How to use delegate methods of singleton/shared class? There is one singleton class having some protocol defined but I'm not getting how to access the delegate functions in other classes.
代码段供参考(迅速):
Code snippet for a reference (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() {}
强制仅通过使用其共享实例访问该类。
That leads to enforce to access the class only by using its shared instance.
2-如 Max的答案,委托应该是可选的,并且具有弱引用。
2- As mentioned in Max's Answer, the delegate should be optional and has a weak reference.
3-协议应为 class 类型,如下所示:
3- The protocol should be a type of class, as follows:
protocol AClassDelegate: class
有关更多信息,您可能需要检查此问题与解答。
现在,为了进行测试,我们假设 method1()在
> A 类: foo()
时应调用 AClassDelegate
中的
Now, let's assume -for testing purposes- that the method1()
from AClassDelegate
should be get called when calling 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")
}
}
输出应为:
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
*/
这篇关于Swift中的单例类的委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!