解除分配 UINavigationController 后内存保持高电平



我在我的应用程序中得到了UINavigationController,rootVC"VC1",VC1包含一个集合视图,每个单元格内有2个图像。当用户选择单元格时,导航控制器会将图像从单元格传递到新的vc"VC2",然后将其推送到导航控制器的顶部。我的问题是当我通过popviewcontroller关闭VC2时,VC2被正确释放,但内存保持在相同的更高级别(推送新vc后,它从60mb增加到130mb(。我尝试将图像设置为 nil,并且图像视图也不起作用。这是我的一些代码:

class VC1: UIViewController {
 var selectedUserPollDetails : VC2?
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let cell = collectionView.cellForItem(at: indexPath) as! AppUserCell
    selectedUserPollDetails = VC2()
    selectedUserPollDetails?.leftPhoto = cell.leftImageNode.image
        selectedUserPollDetails?.rightPhoto = cell.rightImageNode.image
        navigationController?.pushViewController(selectedUserPollDetails !, animated: true)
}
}
class VC2: UIViewController {
lazy var arrow : ArrowBack = {
    let arrow = ArrowBack()
    return arrow
}()
weak var leftPhoto: UIImage?
weak var rightPhoto: UIImage?
 var leftPhotoImageview: UIImageView = {
    let imageview = UIImageView()
    imageview.contentMode = .scaleAspectFill
    imageview.layer.cornerRadius = 5
    imageview.layer.masksToBounds = true
    return imageview
}()
 var rightPhotoImageview: UIImageView = {
    let imageview = UIImageView()
    imageview.contentMode = .scaleAspectFit
    imageview.layer.cornerRadius = 5
    imageview.clipsToBounds = true
    return imageview
}()
override func viewDidLoad() {
    super.viewDidLoad()
view.addSubview(leftPhotoImageview)
    view.addSubview(rightPhotoImageview)
  view.addSubview(arrow)
    arrow.addTarget(self, action: #selector(handleArrowBack), for: .touchUpInside)
}
func handleArrowBack(){
    navigationController?.popViewController(animated: true)
}
override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    leftPhotoImageview.frame = CGRect(x: 100, y: 0, width: 100, height: 100)
    rightPhotoImageview.frame = CGRect(x: 100, y: 200, width: 100, height: 100)
    if leftPhoto != nil, rightPhoto != nil{
        leftPhotoImageview.image = leftPhoto
        rightPhotoImageview.image = rightPhoto
    }
}
deinit{
    leftPhoto = nil
    rightPhoto = nil
    leftPhotoImageview.image = nil
    rightPhotoImageview.image = nil
}

我什至在最后添加了deinit,以确保照片被解除分配。所以基本上当我尝试再次推送 VC2 时(在弹出后(,内存量再次翻倍(260mb(等等......是什么导致了这个问题?我做错了什么?顺便说一句。我省略了不太重要的函数和变量

你确实有内存泄漏。我相信每次您通过导航控制器推送一个新视图,它会创建一个全新的视图,即该视图是全新的,不会重复使用。如果你在你推送到的视图中有很强的引用,除非你去看,否则它们不会被释放,因为它们有一个强大的引用来查看你推送的视图,所以它们徘徊不去。你提到你设计了这些项目。您是否也尝试过将 leftPhotoImageView 和 rightPhotoImageView 也标记为弱属性?似乎有什么东西在坚持这些图像。

您也可以将deinit更改为leftPhotoImageview = nil和rightPhotoImageView = nil,而不是将imageview.image属性设置为nil(如果这有意义的话(。

好的,我想我找到了解决方案,我不知道为什么我没有尝试这个,所以我将我的 imageview 标记为懒惰,现在弹出 vc 后内存正在减少

最新更新