假设我有两个类和两个这样的函数:

public class DataContainer {
    let someData = NSMutableData()
}
public class SuperContainer {
    let someDataContainer = DataContainer()
}

func subFunc(someDataContainer: DataContainer) {
    // Is someSuperContainer guaranteed to be alive?
    // Or may it have been released and only someDataContainer is still alive,
    //    because someSuperContainer is not referenced anymore?

    ... do something with someDataContainer ...
}
func superFunc() {
    let someSuperContainer = SuperContainer()
    subFunc(someSuperContainer.someDataContainer)
}

是否保证someSuperContainersubFunc返回之前是有效的,或者在输入subFunc之后可能会因为它不再被引用而被释放?
编辑:
更好的例子(我试图保持问题的一般性,但现在我认为最好包括一个真实的例子):
public class DataContainer {
    let someData = NSMutableData()
    deinit {
        memset_s(someData.mutableBytes, someData.length, 0x00, someData.length)
    }
}

func doSomethingWithData(data: NSMutableData) {
    // Is DataContainer guaranteed to be still alive?
    // Or may it have been released and `data` zeroed-out,
    //    because someSuperContainer is not referenced anymore
    //    (and was deinitialized and released)?

    ... do something with data ...
}
func someFunc() {
    let dataContainer = DataContainer()
    doSomethingWithData(dataContainer.someData)
}

最佳答案

任何变量或类在其作用域结束之前都是可用的和活动的。在你的例子中,某个超级容器有一个超级容器的范围。当超级飞航结束时,超级飞航也会结束。

func superFunc() {
    let someSuperContainer = SuperContainer()
    subFunc(someSuperContainer.someDataContainer)
    // someSuperContainer will cease to exist once this func completes.
}

关于swift - 属性访问期间的ARC生命周期,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35976332/

10-11 16:31