【问题标题】:App crashes after receiving memory warning due to images loading由于图像加载而收到内存警告后应用程序崩溃
【发布时间】:2015-06-14 21:47:28
【问题描述】:

我正在开发我的第一个应用程序,用户可以在其中保存 13 个屏幕截图并在一个视图控制器(全尺寸图像)之间滑动,并将它们一起显示为另一个视图控制器上的缩略图。以上是我保存图像的方式:

let fileName:String = self.stickerUsed + ".png"
var arrayPaths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString
var pngFileName = arrayPaths.stringByAppendingPathComponent(fileName)
UIImagePNGRepresentation(screenshot).writeToFile(pngFileName, atomically:true)
NSUserDefaults.standardUserDefaults().setObject(fileName, forKey: self.stickerUsed)
NSUserDefaults.standardUserDefaults().synchronize()

以下是我检索图像的方式。这是第一个屏幕截图的代码,并将其设置为 UIImageView 中的图像(对其他 12 个 UIImageView 进行类似操作):

    var defaultName:String = "Sticker1.png"
    let path = NSSearchPathForDirectoriesInDomains(
        .DocumentDirectory, .UserDomainMask, true)[0] as NSString
    let fileName = NSUserDefaults.standardUserDefaults()
        .stringForKey("Sticker1") ?? defaultName
    let imagePath = path.stringByAppendingPathComponent(fileName)
    let image = UIImage(contentsOfFile: imagePath )
    Sticker1_view.image = resizeImage(image!, newSize: CGSizeMake(overView.frame.width/4, overView.frame.height/4))

这是我将它们加载到内存后缩小它们的方式:

      func resizeImage(image: UIImage, newSize: CGSize) -> (UIImage) {
    let newRect = CGRectIntegral(CGRectMake(0,0, newSize.width, newSize.height))
    let imageRef = image.CGImage

    UIGraphicsBeginImageContextWithOptions(newSize, false, 0)
    let context = UIGraphicsGetCurrentContext()

    // Set the quality level to use when rescaling
    CGContextSetInterpolationQuality(context, kCGInterpolationHigh)
    let flipVertical = CGAffineTransformMake(1, 0, 0, -1, 0, newSize.height)

    CGContextConcatCTM(context, flipVertical)
    // Draw into the context; this scales the image
    CGContextDrawImage(context, newRect, imageRef)

    let newImageRef = CGBitmapContextCreateImage(context) as CGImage
    let newImage = UIImage(CGImage: newImageRef)

    // Get the resized image from the context and a UIImage
    UIGraphicsEndImageContext()

    return newImage!
}

该应用第一次运行良好。但是当我在两个视图控制器之间切换时,它会变慢,最终我会收到一个导致崩溃的内存警告。从我的研究中了解到,我的图像正在被缓存。我需要清除我的缓存或不要多次加载我的图像。或者也许在 didReceiveMemoryWarning() 中做一些事情以阻止它崩溃。我该怎么办?

【问题讨论】:

    标签: ios xcode swift ipad uiimageview


    【解决方案1】:

    您可以使用 profile(Product->Profile) 来查看您的程序是否存在内存泄漏。

    你可以看看这个tutorial

    希望这可以帮助您解决内存问题。

    【讨论】:

      【解决方案2】:

      经过一夜的尝试。我设法阻止了应用程序的减速和崩溃。 因为我在应用程序中多次使用图像。最好使用:

      let image = UIImage(named: imagePath )
      

      代替:

      let image = UIImage(contentsOfFile: imagePath )
      

      以这种方式缓存图像并将其带到前面。应用不再崩溃

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-08-08
        • 1970-01-01
        • 2015-04-01
        • 2012-11-28
        • 2013-11-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多