まず、私がポイントしたい:
の1-シングルトンクラスの作成すべき含まれています強制につながる
private init() {}
だけその共有インスタンスを使用してクラスにアクセスします。
Max's Answerで述べたよう
2-、デリゲートは任意であると弱い基準を有するべきです。
protocol AClassDelegate: class
詳細については、あなたがこのQ&Aチェックすることをお勧めします:次のように
、3-プロトコルは、クラスのタイプでなければなりません。今
、テストはA
クラスからfoo()
を呼び出すときにAClassDelegate
からmethod1()
が呼び出されるべきであることpurposes- -forのは想定してみましょう:
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
*/
希望する必要があります。
参加者は常に弱いはずです。 –
クラスAにプライベートinit()を追加して、常にシングルトンとして使用するようにしてください。現在、あなたはシングルトンではないA()も宣言することができます。 – totiG
アドバイス:あなたのシングルトンのデリゲートを設定するクラス(クラスBなど)は許可しないでください。シングルトンがinit()時に使用するデリゲートを渡すことを強く検討する。あなたのシングルトンはデリゲートのメソッド1を呼び出して、何かを実行します。デリゲートとしてのクラスBは、シングルトンを設定する(または実際に呼び出す)べきではありません。 –