別のクラスで弱い参照クラスを作成しようとしています。最初のクラスの init で、2 番目のクラスのインスタンスを作成して関数で使用しますが、init 関数が完了すると、2 番目のクラスが破棄されて nil が返されます。コード例を次に示します。
//: Playground - noun: a place where people can play
import UIKit
class A {
weak var b : B?
init(){
NSLog("a Created")
self.b = B()
}
deinit{
NSLog("a Destroyed")
}
}
class B {
var arrayOfA : Array <A> = []
init(){
NSLog("b Created")
}
deinit{
NSLog("b Destroyed")
}
func printSomething(){
NSLog("print Something")
}
}
func test(){
let a : A = A()
a.b?.printSomething()
NSLog("still in test()")
}
test()
コンソールでこれを見る
2016-04-04 00:34:50.516 MyPlayground[20009:921709] が作成されました
2016-04-04 00:34:50.516 MyPlayground[20009:921709] b 作成
2016-04-04 00:34:50.516 MyPlayground[20009:921709] b 破壊されました
2016-04-04 00:34:50.527 MyPlayground[20009:921709] まだテスト中 ()
2016-04-04 00:34:50.527 MyPlayground[20009:921709] 破壊された
printSomething() を呼び出すと nil が返されます
Aクラスの外にBクラスを作成したくないし、メモリリークの問題にも弱い。
2つのSwiftクラス間の1対多の関係が必要なため、関数からデータをロードできます