1

我试图在另一个类中创建弱引用类,在第一类的初始化中我创建第二类的实例以在函数中使用它,但是在初始化函数完成后,第二类被销毁并返回 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 类,而且我希望它对于内存泄漏问题很弱。

一些我想要两个快速类之间的一对多关系,所以我可以从函数加载数据

4

1 回答 1

1

由于您声明bweak,因此一旦超出范围就会被释放。在这种情况下,只要这段代码:

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()

于 2016-04-03T21:29:31.650 回答