【问题标题】:GPUImage and GPUImageView : App terminated due to memory errorGPUImage 和 GPUImageView :应用程序因内存错误而终止
【发布时间】:2015-07-10 22:21:36
【问题描述】:

我正在使用一个 GPUImage 和许多 GPUImageView 实例。目的是显示原始图像,在顶部分层几片过滤图像,最后在原始图像上缓慢地为切片过滤器设置动画。想象一张图像,其中有一些棕褐色条滚动,以分段显示正常图像和棕褐色图像。

我将此功能包装在 UIView 的子类中,如下所示:

import Foundation
import QuartzCore

class FilteredImageMaskView : UIView {

init(frame: CGRect, image: UIImage){
    super.init(frame: frame);

    let imageViewFrame = CGRectMake(frame.origin.x, 0.0, frame.size.width, frame.size.height);

    let origImage = GPUImagePicture(image: image);
    origImage.forceProcessingAtSizeRespectingAspectRatio(imageViewFrame.size);

    // Display the original image without a filter
    let imageView = GPUImageView(frame: imageViewFrame);
    origImage.addTarget(imageView);
    origImage.processImageWithCompletionHandler(){
        origImage.removeAllTargets();

        var contentMode = UIViewContentMode.ScaleAspectFit;
        imageView.contentMode = contentMode;

        // Width of the unfiltered region
        let regularWidth: CGFloat = 30.0;
        // Width of filtered region
        let filterWidth: CGFloat = 30.0;

        // How much we are moving each bar
        let totalXMovement = (regularWidth + filterWidth) * 2;

        // The start X position
        var currentXForFilter: CGFloat = -totalXMovement;

        // The filter being applied to an image
        let filter = GPUImageSepiaFilter();
        filter.intensity = 0.5;
        // Add the filter to the originalImage
        origImage.addTarget(filter);

        let filteredViewCollection = FilteredViewCollection(filteredViews: [GPUImageView]());

        // Iterate over the X positions until the whole image is covered
        while(currentXForFilter < imageView.frame.width + totalXMovement){
            let frame = CGRectMake(currentXForFilter, imageViewFrame.origin.y, imageViewFrame.width, imageViewFrame.height);
            var filteredView = GPUImageView(frame: frame);
            filteredView.clipsToBounds = true;
            filteredView.layer.contentsGravity = kCAGravityTopLeft;

            // This is the slice of the overall image that we are going to display as filtered
            filteredView.layer.contentsRect = CGRectMake(currentXForFilter / imageViewFrame.width, 0.0, filterWidth / imageViewFrame.width, 1.0);
            filteredView.fillMode = kGPUImageFillModePreserveAspectRatio;

            filter.addTarget(filteredView);

            // Add the filteredView to the super view
            self.addSubview(filteredView);

            // Add the filteredView to the collection so we can animate it later
            filteredViewCollection.filteredViews.append(filteredView);

            // Increment the X position           
            currentXForFilter += regularWidth + filterWidth;
        }

        origImage.processImageWithCompletionHandler(){
            filter.removeAllTargets();

            // Move to the UI thread
            ThreadUtility.runOnMainThread(){
                // Add the unfiltered image
                self.addSubview(imageView);
                // And move it behind the filtered slices
                self.sendSubviewToBack(imageView);

                // Animate the slices slowly across the image
                UIView.animateWithDuration(20.0, delay: 0.0, options: UIViewAnimationOptions.Repeat, animations: { [weak filteredViewCollection] in
                    if let strongfilteredViewCollection = filteredViewCollection {
                        if(strongfilteredViewCollection.filteredViews != nil){
                            for(var i = 0; i < strongfilteredViewCollection.filteredViews.count; i++){
                                strongfilteredViewCollection.filteredViews[i].frame.origin.x += totalXMovement;
                                strongfilteredViewCollection.filteredViews[i].layer.contentsRect.origin.x += (totalXMovement / imageView.frame.width);
                            }
                        }
                    }
                }, completion: nil);
            }
        }
    }
}

required init(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder);
}

}

class FilteredViewCollection {
    var filteredViews: [GPUImageView]! = [GPUImageView]();

    init(filteredViews: [GPUImageView]!){
        self.filteredViews = filteredViews;
    }
}

FilteredImageMaskView 的实例以编程方式添加到 viewController 中的视图中。当 viewController 被解除时,假设资源将被处理——我小心翼翼地避免了保留周期。当我在真实设备上的调试器中观察内存消耗时,当 viewController 被关闭时,内存确实会适当下降。但是,如果我反复加载那个viewController来查看图像,然后将其关闭,然后再次重新加载,我最终会遇到“App因内存错误而终止”

如果我在关闭 viewController 后等待一段时间,内存错误似乎不那么频繁,这让我相信在 viewController 关闭后内存仍在释放......?但是我在 viewController 的打开和关闭不那么快的几次之后也看到了错误。

我一定是在低效使用 GPUImage 和/或 GPUImageView,我正在寻求指导。

谢谢!

编辑:请参阅下面的视图控制器实现。

import UIKit

class ViewImageViewController: UIViewController, FetchImageDelegate {

    var imageManager = ImageManager();

    @IBOutlet var mainView: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()

        imageManager.fetchImageAsync(delegate: self);
    }

    // This callback is dispatched on the UI thread
    func imageFetchCompleted(imageData: [UInt8]) {
        let imageView = FilteredImageMaskView(frame: self.mainView.frame, image: UIImage(data: imageData));
        mainView.addSubview(imageView);

        var timer = NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(10.0), target: self, selector: Selector("displayReminder"), userInfo: nil, repeats: false);
    }

    func displayReminder(){
        // Show an alert or message here
    }

}

class ImageManager {

    func fetchImageAsync(delegate: FetchImageDelegate) {
        // This dispatches a high priority background thread
        ThreadUtility.runOnHighPriorityBackgroundThread() { [weak delegate] in
            // Get the image (This part could take a while in the real implementation)
            var imageData = [UInt8]();

            // Move to the UI thread
            ThreadUtility.runOnMainThread({
                if let strongDelegate = delegate {
                    strongDelegate.imageFetchCompleted(imageData);
                }
            });
        }
    }
}

现在我正在查看这个精简版本,是否将 self 传递给 ImageManager 会创建一个保留周期,即使我将 weakly 引用到后台线程?我可以从ViewImageViewController 将其作为弱引用传递吗?在 fetchImageAsync 方法完成并调用回调之前,ViewImageViewController 肯定有可能被解除。

编辑:我想我找到了问题所在。如果您查看回调中的ViewImageViewController,我会创建一个 NSTimer 并传递 self.我的怀疑是,如果在计时器执行之前关闭 viewController,则会创建一个保留周期。这可以解释为什么如果我多等几秒钟,我不会收到内存错误 - 因为计时器触发并且 viewController 正确处理。这是解决方法(我认为)。

// This is on the ViewImageViewController
var timer: NSTimer!;

// Then instead of creating a new variable, assign the timer to the class variable
self.timer = NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(10.0), target: self, selector: Selector("displayReminder"), userInfo: nil, repeats: false);

// And finally, on dismiss of the viewcontroller (viewWillDisappear or back button click event, or both)
func cancelTimer() {
    if(self.timer != nil){
        self.timer.invalidate();
        self.timer = nil;
    }
}

【问题讨论】:

  • 你能提供更多关于视图控制器的信息吗?它实际上被释放了吗?如果您有内存泄漏,问题根本就不是您显示的代码。
  • 当然可以。我会更新 OP。
  • @matt 根据您的要求添加...您可能是对的...见上文
  • 很确定我是通过更仔细地查看 VC 得到的。感谢您的提示和指导。现在彻底测试。

标签: ios swift memory-management gpuimage


【解决方案1】:

我想我找到了问题所在。如果您查看回调中的ViewImageViewController,我会创建一个 NSTimer 并传递 self.我的怀疑是,如果在计时器执行之前关闭 viewController,则会创建一个保留周期。这可以解释为什么如果我多等几秒钟,我不会收到内存错误 - 因为计时器触发并且 viewController 正确处理。这是解决方法(我认为)。

// This is on the ViewImageViewController
var timer: NSTimer!;

// Then instead of creating a new variable, assign the timer to the class variable
self.timer = NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(10.0), target: self, selector: Selector("displayReminder"), userInfo: nil, repeats: false);

// And finally, on dismiss of the viewcontroller (viewWillDisappear or back button click event, or both)
func cancelTimer() {
    if(self.timer != nil){
        self.timer.invalidate();
        self.timer = nil;
    }
}

【讨论】:

  • 很有可能。请参阅我对计时器和保留周期的讨论 - 从本节开始大约 2/3:apeth.com/iOSBook/… 正如我引用的文档,“目标对象由计时器保留并在计时器无效时释放。”我的例子是一个重复计时器;我没有想到永远没有机会开火的单发长间隔计时器的例子!我会给自己做个笔记,以将其包含在本书的任何未来版本中。
  • @matt 确实这似乎是问题所在。现在,自从实现了上面的代码以来,一切都得到了正确的处理。有时需要一把细齿梳子和一些耐心才能找到这些讨厌的保留物:-D
  • 嗯,这需要找对地方。你找错地方了;您的 GPUImage 内容完全是一条红鲱鱼,我是那个告诉您并让您找到正确位置的人。但是我告诉你这是免费的,所以最后你扔掉了自己的100分,没有任何目的!
  • 是的.. 有点希望我没有开始赏金。或者,您可以奖励给指出正确方向的人。
  • 好吧,显然我本可以给你写我的建议 - 这是泄漏的视图 controller - 作为答案而不是评论,以试图获得赏金。但我不会费心去做那件事。 :) 毕竟,您确实实际上找到了答案。所以当我支持你这样做时,你从我这里得到了 10 分。 :)))) 但教训是:思考胜于设置赏金。
【解决方案2】:

FilteredImageMaskView在processImageWithCompletionHandler的block中被强引用,很可能形成retain循环。尝试在块中使用弱自我

【讨论】:

    猜你喜欢
    • 2015-12-21
    • 2014-02-23
    • 1970-01-01
    • 1970-01-01
    • 2015-05-06
    • 2015-09-22
    • 2015-07-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多