我试图在另一个类中创建弱引用类,在第一类的初始化中我创建第二类的实例以在函数中使用它,但是在初始化函数完成后,第二类被销毁并返回 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 类,而且我希望它对于内存泄漏问题很弱。
一些我想要两个快速类之间的一对多关系,所以我可以从函数加载数据