6

我正在尝试将用户相册中的所有图像加载到我的应用程序的收藏视图中,但在加载了其中一些后,应用程序将自行关闭并返回主菜单。与 XCode 的连接也断开了。这不会发生在模拟器中,而只会发生在我正在测试的 iPhone 4s 中。在它崩溃之前出现的错误消息是,按照发生的顺序,

  1. 收到内存警告
  2. 与 assetsd 的连接中断或 assetsd 死机。

我已经收集了我认为导致此问题的代码的几个部分。

var imgFetchResult: PHFetchResult!

override func viewDidLoad() {
    super.viewDidLoad()
    let fetchOptions = PHFetchOptions()
    fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)]

    let fetchResult = PHAsset.fetchAssetsWithMediaType(PHAssetMediaType.Image, options: fetchOptions)

    if fetchResult.count > 0
    {
        println("images found ? \(fetchResult.count)")
        self.imgFetchResult = fetchResult
    }
}

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
{
    println("cellForItemAtIndexPath")
    let cell: PhotoThumbnailCollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as PhotoThumbnailCollectionViewCell

    println("indexpath is \(indexPath.item)")

    if( indexPath.item == 0 )
    {
        cell.backgroundColor = UIColor.redColor() //temp placeholder for camera image
    }
    else
    {
        let asset: PHAsset = self.imgFetchResult[indexPath.item] as PHAsset 
        PHImageManager.defaultManager().requestImageForAsset(asset, targetSize: PHImageManagerMaximumSize, contentMode: .AspectFill, options: nil, resultHandler: {(result, info) in cell.setThumbnailImage(result)
        })
    }

    return cell
}

我相信我需要释放内存,但不确定要释放什么。似乎是正在加载到集合视图的单元格中的图像。

我还发现集合视图不超过 4 个图像。在第四张图片之后,发生了崩溃。此外,图像未按顺序加载。

4

2 回答 2

8

在这行代码中发现了问题

PHImageManager.defaultManager().requestImageForAsset(asset, targetSize: PHImageManagerMaximumSize, contentMode: .AspectFill, options: nil, resultHandler: {(result, info) in cell.setThumbnailImage(result)
})

参数,targetSize被传递的值PHImageManagerMaximumSize是罪魁祸首。我更改它以CGSize(width: 105, height: 105)解决问题。

根据文档PHImageManagerMaximumSize

当您使用 PHImageManagerMaximumSize 选项时,照片会为资源提供可用的最大图像,而无需缩放或裁剪。(也就是说,它忽略了 resizeMode 选项。)

所以,这就解释了问题。我相信如果它是单个图像,它应该不是问题,但如果它是多个图像,则设备会耗尽内存。

我希望这对其他人有所帮助。

于 2015-03-03T08:43:39.157 回答
0

正如@winhung 所说,对我来说它也是大小。我所做的是将目标大小减少一半,例如:

let asset: PHAsset = self.imgFetchResult[indexPath.item] as PHAsset 
let mytargetSize = CGSize(width: asset.pixelWidth/2, height: asset.pixelHeight/2)

PHImageManager.defaultManager().requestImageForAsset(asset, targetSize: mytargetSize, contentMode: .AspectFill, options: nil, resultHandler: {(result, info) in cell.setThumbnailImage(result)
})
于 2017-10-10T17:12:20.390 回答