MFMailComposeViewController uses too much memory

2019-06-02 18:50发布

When I try to send images as attachements(summar size ~4mb) by using MFMailCompose, activity monitor says, what 100(+-2)mb of memory is used. After sending or cancelling memory is freeing ~20 megabytes, but what happened to the remaining 80 megabytes if shared item with images is deallocated? Thanks!:)

1条回答
孤傲高冷的网名
2楼-- · 2019-06-02 19:39

An image's file size and the amount of memory it consumes when displayed are two completely different things.

Images such as JPEGs and PNGs are compressed. When they are drawn to the screen they are uncompressed.

A quick rule of thumb to figure out how much memory an image will consume when displayed is

memory consumed = (width * height) * 4

Example, a image that is 2 KB on disk, but is 62 x 52 pixels will actually consume 12,896 bytes or 12 KB. I imagine an image that is 4 MB on disk will consume a lot more than 4 MBs.

The problem is that MFMailComposer displays the images in it's compose view when you add them as attachments and as a result they are decompressed, consuming memory. So your 4 MBs of images actually consume a lot more than you think they do.

Perhaps try sending only one image at a time. You also need to be conscious that you're releasing the images and the MFMailComposeViewController when you're done with them, or that would surely be the source of the leak.

Also be aware of how you initially load your images. UIImage's imageNamed: method actually caches images. Cached images are only purged in low memory situations, so they can hang around for a while if you're not hitting the limits.

Finally, you've noted that you're seeing the memory consumption in Instruments, but have you actually verified that it is actually a problem? Are you experiencing app crashes due to low memory when testing your app while it is not connected to Instruments or the debugger?

No body is perfect - and that goes for Apple too. There have been documented cases in the past where Apple's frameworks have shown memory leaks (UIImage's caching leaked in iOS 2.x), but I wouldn't be so quick to blame the frameworks when you notice a spike in memory consumption. If the leaks instrument is not showing any leaks, and the analyser isn't showing any issues, the likeliest scenario is that it's just simply memory consumption and not a leak.

Its important to remember that iOS devices don't have gigabytes of RAM like computers do. You need to be conservative with the memory that you use. If that means not sending XX MBs of images at the same time, then that's the way it has to be.

查看更多
登录 后发表回答