Monday, April 22, 2013

Releasing AVPlayerLayer and AVPlayer

While using AVPlayerLayer and AVPlayer together, I found that the retainCount of the AVPlayer object is not decremented immediately upon destroying the associated AVPlayerLayer. It seems to be scheduled some time later. If I release them in applicationDidEnterBackground: the free-up progress will just stopped (and the app entered into background) before the freeing is completed. This caused some problems in my project. After some searching, I found that beginBackgroundTaskWithExpirationHandler: allows running background task and so it gives time for the non-finished free-up task. I simply adding it to applicationDidEnterBackground: and the free-up is done completely.
- (void)applicationDidEnterBackground:(UIApplication *)application
    UIBackgroundTaskIdentifier identifier = UIBackgroundTaskInvalid;
    identifier = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
        [[UIApplication sharedApplication] endBackgroundTask:identifier];

Update: After some searching and trying, I found that a better way is to listen to UIApplicationDidEnterBackgroundNotification event in my class, and I do not need to use the background task hack anymore then.
[[NSNotificationCenter defaultCenter] addObserver:self