假设我有两个类和两个这样的函数:
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)
}
在someSuperContainer
返回之前subFunc
保证有效吗?或者在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)
}
答案 0 :(得分:2)
在范围结束之前,任何变量或类都可用并且处于活动状态。在您的情况下,someSuperContainer的范围为superFunc。当superFunc结束时,someSuperContainer也将如此。
func superFunc() {
let someSuperContainer = SuperContainer()
subFunc(someSuperContainer.someDataContainer)
// someSuperContainer will cease to exist once this func completes.
}