【发布时间】:2016-11-04 05:38:33
【问题描述】:
我有以下功能:
func attachToComment(_ data: Data, url: URL?, type: MediaType) {
self.dismiss(animated: true, completion: nil)
let image = UIImage(data: data)!
model.attachmentData = data
model.attachmentVideoURL = url
model.attachmentType = type
toolbar.attachImage(image, withType: type)
}
这是传递给以模态方式呈现的视图控制器的引用:
containerNavViewController.attachToComment = attachToComment
ContainerNavViewController 是一个UINavigationController,里面有一个容器视图控制器。这显示了相机,一旦拍摄了图像,将 attachToComment 函数传递给下一个视图控制器 - EditImageViewController。在 ContainerNavViewController 我有以下代码:
var attachToComment: ((_ data: Data, _ url: URL?, _ type: MediaType) -> ())?
var model = CameraModel()
....
editImageViewController.attachToComment = self.attachToComment
editImageViewController.model = model
self.navigationController?.pushViewController(editImageViewController, animated: false)
在 EditImageViewController 内部,我有以下调用闭包的代码:
attachToComment(model.imageData, model.videoURL, model.mediaType)
然后调用原始函数并关闭模态视图控制器。但是,这些视图不会调用 deinit,它们在后台非常“活跃”。我的内存泄漏在哪里,我该如何预防?
【问题讨论】:
-
看起来您可能正在进行一个保留周期。 Self 强烈拥有 attachToComment(闭包是一流的对象),在闭包内您引用 self 和 self 拥有的变量(模型、工具栏和函数解除)。结果,self 拥有闭包,闭包强烈地捕获了 self,现在两者都不会释放,因为它们相互保留。