xcodedidreceivememorywarningavcam

AVCam memory low warning


This is less a question and more a record of what I've found around the AVCam sample code provided by Apple for iOS4 and 5 camera manipulation. The symptoms of the problem for me were that my app would crash on launching the AVCamViewController after taking around 5-10 photos.

I ran the app through the memory leak profiler and there were no apparent leaks but on inspection with the Activity Monitor I discovered that something called mediaserverd was increasing by 17Mb every time the camera was launched and when it reached ~100Mb the app crashed with multiple low memory warnings.


Solution

  • Apple revised the sample code on Oct 17 2013, fixing the retain cycle. The issue is due to a improper usage of self within the blocks defined in the init.

    Here's the revision description

    Fixed retain cycles in AVCaptureManager that result in leaks. NOTE - if you've adapted AVCam code in your app, you should adopt the fixes made here in AVCaptureManager.m's init method. Without these fixes, you may be leaking AVCaptureManager instances and leaving the camera running constantly while your app is in the foreground.


    However, the fix they introduced only works in case of Manual Retain Count. If you are using ARC on the project, apart from getting rid of release/retain calls and other obvious things, the storage qualifier for weakSelf has to be changed from __block to __weak, like follows.

    __weak AVCamCaptureManager *weakSelf = self;
    

    In fact the semantic of __block changed with ARC. In MRC it caused the variable to be weakly referenced, wheres in ARC it does not and __weak must be used for this purpose.

    More information about this topic can be found here: How do I avoid capturing self in blocks when implementing an API?

    Using the new init implementation from the last revision and using __weak instead of __block, finally caused the dealloc method to be properly called.


    Finally, for those who hate to carry around old legacy code, here's a modernized version of the AVCam project: https://github.com/Gabro/AVCam

    Features: