class return 中的弱引用在第一个 class 的 init 中创建时为 nil
Weak Refrence in class return nil when created in first class's init
我试图在另一个 class 中创建弱引用 class,在第一个 class 的初始化中,我创建了第二个 class 的实例以在函数中使用它,但是在初始化函数完成后,第二个 class 被销毁并且 return 为零,
这是一个示例代码
//: 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] a Created
2016-04-04 00:34:50.516 MyPlayground[20009:921709] b Created
2016-04-04 00:34:50.516 MyPlayground[20009:921709] b Destroyed
2016-04-04 00:34:50.527 MyPlayground[20009:921709] still in test()
2016-04-04 00:34:50.527 MyPlayground[20009:921709] a Destroyed
调用 printSomething() 将 return nil
我不想在 A class 之外创建 B class,而且我希望它因内存泄漏问题而变弱。
有些我想要两个 swift class 之间的一对多关系,所以我可以从函数
加载数据
由于您将 b
声明为 weak
,一旦它超出范围,它就会被释放。在这种情况下,一旦此代码:
init(){
NSLog("a Created")
self.b = B()
}
完成执行,self.b
被销毁。这是预期的行为。如果您希望 b
在 init
之后停留,那么您应该将其保留为 strong
。
或者您可以这样做:
func test(){
let b : B = B()
let a : A = A(b:b)
a.b?.printSomething()
NSLog("still in test()")
}
在 A
中,您可以制作一个特殊的 init
来接收 B
:
init(b: B){
NSLog("a Created")
self.b = b
}
使用这段代码,A
对 B
的引用仍然很弱,但是由于 B
仍然存在于 test()
方法中,它也在那里当调用 printSomething()
时。
我试图在另一个 class 中创建弱引用 class,在第一个 class 的初始化中,我创建了第二个 class 的实例以在函数中使用它,但是在初始化函数完成后,第二个 class 被销毁并且 return 为零, 这是一个示例代码
//: 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] a Created
2016-04-04 00:34:50.516 MyPlayground[20009:921709] b Created
2016-04-04 00:34:50.516 MyPlayground[20009:921709] b Destroyed
2016-04-04 00:34:50.527 MyPlayground[20009:921709] still in test()
2016-04-04 00:34:50.527 MyPlayground[20009:921709] a Destroyed
调用 printSomething() 将 return nil
我不想在 A class 之外创建 B class,而且我希望它因内存泄漏问题而变弱。
有些我想要两个 swift class 之间的一对多关系,所以我可以从函数
加载数据由于您将 b
声明为 weak
,一旦它超出范围,它就会被释放。在这种情况下,一旦此代码:
init(){
NSLog("a Created")
self.b = B()
}
完成执行,self.b
被销毁。这是预期的行为。如果您希望 b
在 init
之后停留,那么您应该将其保留为 strong
。
或者您可以这样做:
func test(){
let b : B = B()
let a : A = A(b:b)
a.b?.printSomething()
NSLog("still in test()")
}
在 A
中,您可以制作一个特殊的 init
来接收 B
:
init(b: B){
NSLog("a Created")
self.b = b
}
使用这段代码,A
对 B
的引用仍然很弱,但是由于 B
仍然存在于 test()
方法中,它也在那里当调用 printSomething()
时。