运行以下代码时发生内存泄漏。我甚至没有使用或持有newImage
对象。
for image in imageArray {
autoreleasepool {
let newImage = image.scalingWith(targetSize: CGSize(width: 500, height: 500))
}
}
以下是UIImage
扩展名中的缩放方法:
func scaleWith(targetSize: CGSize, backgroundColor: UIColor = UIColor
.white) -> UIImage? {
let imageSize = size
var scaleFactor: CGFloat = 0.0
let scaledWidth = targetSize.width
let scaledHeight = targetSize.height
var thumbnailPoint = CGPoint.zero
if imageSize.equalTo(targetSize) { return self }
let widthFactor = targetSize.width / imageSize.width
let heightFactor = targetSize.height / imageSize.height
if widthFactor > heightFactor {
scaleFactor = heightFactor
thumbnailPoint.x = (targetSize.width - scaleFactor * imageSize.width) * 0.5;
} else {
scaleFactor = widthFactor
thumbnailPoint.y = (targetSize.height - scaleFactor * imageSize.height) * 0.5;
}
UIGraphicsBeginImageContext(CGSize(width: scaledWidth, height: scaledHeight))
let context = UIGraphicsGetCurrentContext()
let bounds = CGRect(x: 0, y: 0, width: scaledWidth, height: scaledHeight)
context!.setFillColor(backgroundColor.cgColor)
context!.fill(bounds)
var thumbnailRect = CGRect.zero
thumbnailRect.size.width = imageSize.width * scaleFactor;
thumbnailRect.size.height = imageSize.height * scaleFactor;
thumbnailRect.origin = thumbnailPoint
draw(in: thumbnailRect)
let resultImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext();
return resultImage
}
有人能给我一些建议吗?
答案 0 :(得分:0)
通常,在启用了内存泄漏的仪器中运行此代码相当容易。此外,您需要在设备上运行它,因为在模拟器上运行它会产生错误的结果。 Xcode中存在一个错误,即在调试模式和使用控制台时它没有释放对象。
再次:在设备上运行仪器。代码看起来不错,应该没有内存泄漏。 考虑到该循环中的代码,还需要autoreleasepool吗?