I'm using a UIImageView to display album artwork when playing music. Every time new artwork is loaded, the memory usage increases. I'm using ARC and tried a autoreleasepool around the code. If I put the app in the background, the cache clears and it starts using up memory again.
Here's my code:
- (void) showArtwork {
@autoreleasepool {
MPMediaItem *currentItem = [self.musicPlayer nowPlayingItem];
if (currentItem) {
MPMediaItemArtwork *artwork = [currentItem valueForProperty: MPMediaItemPropertyArtwork];
if (artwork) {
UIImage *artworkImage = [artwork imageWithSize: CGSizeMake (339, 339)];
if (artworkImage) {
[self.appCoverArt setImage: artworkImage];
}
}
}
}
}
musicPlayer is the systemMusicPlayer
appCoverArt is my UIIMageView
1. Is there a way to release an image from UIImageView before assigning a new image?
2. Is there a way to clear the pool other than putting the app in the background (which does clear the memory)?
With ARC, you release an image from UIImageView
by setting its image property to nil
, or to another instance of UIImage
, provided the retain count of the previous UIImage
drops to zero.
Based on the code you shared, it is unlikely that the memory buildup is being caused by setting a new image on the appCoverArt
variable. Perhaps memory is being retained elsewhere, such as a variable that holds the player's queue?
A great way to find out how memory is being retained is to run Instruments' Allocations tool. Please see Gathering information about memory use and Minimizing your app's Memory Footprint for detailed information.