Reputation: 804
In a view controller I have a UIImageView as a subview. On willRotateToInterfaceOrientation, i replace it with a different UIImageView. If both are in memory at the same time, it sometimes jettison crashes because the images are very big. So i want to make sure I completely dealloc the first one before making the new one. When i call removeFromSuperview on it, I think it is basically autoreleasing at some point later, but I need it to be dealloced immediately.
So it seems i need my own autorelease pool when the UIImageView is created, and then drain it when willRotateToInterfaceOrientation gets called, after the removeFromSuperview call. But the documentation says:
An autorelease pool should always be drained in the same context (such as the invocation of a method or function, or the body of a loop) in which it was created. Autorelease pools are used “inline.” There should typically be no reason why you should make an autorelease pool an instance variable of an object.
So what is the "right" way to do this?
Upvotes: 3
Views: 404
Reputation: 104718
Think of autorelease pools as thread local stacks. You do not persist across contexts or other autorelease pools -- messing up the ordering. Having an autorelease pool as an ivar is often a mistake. Using an autorelease pool from multiple threads is also a mistake.
Create one every place you need it, and destroy in that context, on that thread, without messing up the ordering, and you'll be fine. That may imply creating and destroying one in each method you mentioned. They are quite fast to create and destroy.
If you need to hold a reference to another object (e.g. your image) beyond that context to ensure it lives as long as you need it, do so.
Upvotes: 1
Reputation: 57179
The best thing to do is optimize your images. It is imperative that an autorelease pool is allocated and drained within the same context. First thing you should is try to reduce the size of the image. If they are png's try pngcrush
. If the images are still to large consider using mmap
to load portions of the image at a time.
Impose size limits on resources.
Avoid loading a large resource file when a smaller one will do. Instead of using a high-resolution image, use one that is appropriately sized for iOS-based devices. If you must use large resource files, find ways to load only the portion of the file that you need at any given time. For example, rather than load the entire file into memory, use the mmap and munmap functions to map portions of the file into and out of memory. For more information about mapping files into memory, see File-System Performance Guidelines.
Upvotes: 2