内存问题5原则

来源:互联网 发布:主天使高达淘宝 编辑:程序博客网 时间:2024/05/17 23:14

1. Use virtual memory
iOS doesn’t use swap file but it does support virtual memory. If an app keeps a lot of data in memory for random access (like vocabulary in Letter Blocks 3D) you want to organize it as a mapfile rather then loading it to RAM withmalloc(). An easiest way to do that is to callNSData initWithContentsOfMappedFile:

2. Avoid stacking autoreleased objects
When you instantiate objects like NSString with no explicit allocation they live until the release of your autorelease pool – typically until your app quits. Extensive usage of such techniques may lead to a lot of garbage in RAM. UseNSString initWithContentsOfFile:so you can later release it instead ofNSString stringWithContentsOfFile:. The same rule applies toUIImage imageNamed:– this is not recommended to use for image loading.

3. Handle memory warnings
Unload unnecessary resources when handling memory warning. Even if you can’t unload any of your stuff call[super didReceiveMemoryWarning]in all your UIViewControllers. That will by default free some resources like UI controls on non-front views. Failing to handle this event may make iOS decide that your app deserves killing.

4. Consider limited usage of animated view transitions
Animations like flip transition are noticed to cause RAM usage spikes when executed. This feature is very neat and should be used in many cases but it may trigger memory warnings in a heavily loaded multitasking environment. In particular we strongly recommend to avoid animating OpenGL views.

5. Test your memory footprint on device

Use instruments to test. The most useful tools are Allocations, Leaks and Activity Monitor. Testing on simulator is not relevant in most cases since its memory footprint tends to be completely different. Once you test you can figure out how much RAM each part of your app uses, where are the bottlenecks and how you can optimize.