我通过 Instruments 注意到 NSCollectionView 中存在内存泄漏。当我追踪代码时,它显示了下面的特定行:
collectionView.makeItem(withIdentifier: identifier, for: indexPath) as? DisplayableCellProtocol
然后我在Xcode、内存调试器中查看,发现有一些未引用的项目导致了泄漏。然而,并非所有创建的项目makeItem
漏水,有的正常,有的甚至不显示。
Managed normal unleaked item is like this graph
And the leaked ones are like this (without any connections):
这正常吗,其他人也有同样的问题吗?有谁知道如何正确解决这个问题?这与使用 xib 设计项目视图有什么关系吗?
以下是一些可能有助于理解情况的代码:
func collectionView(_ collectionView: NSCollectionView, itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem {
let data = datasource[indexPath.item]
let identifier: String = "ServiceCell"
// Next line is where the leak occurs
guard let cell = collectionView.makeItem(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: identifier), for: indexPath) as? ServiceCell else {
return ServiceCell(nibName: NSNib.Name("ServiceCell.xib"), bundle: Bundle.main)
}
cell.iconView.image = data.icon
cell.serviceLabel.stringValue = data.name
cell.introLabel.stringValue = data.content
cell.highlighted = false
return cell
}
ServiceCell的定义是:
class ServiceCell: NSCollectionViewItem {
@IBOutlet weak var iconView: NSImageView!
@IBOutlet weak var serviceLabel: NSTextField!
@IBOutlet weak var cmdLabel: NSTextField!
@IBOutlet weak var introLabel: NSTextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
}
}
不确定代码在这里是否有帮助。我试图找出我自己的代码中是否有任何错误,但还没有发现。
Meanwhile, I found a lot of other leaks, and most of them points to the makeItem
line
更新:我又看了一遍。所以每次都会使实际需要的物品数量增加一倍。例如,我需要 2 个单元,它将创建 4 个而不是 2 个,其中两个是泄漏的。有任何想法吗?