简体   繁体   中英

NSMutableArray Clearing after Memory Warning

I have a program that is saving a captured image to a NSMutableArray temporary. Normally this is fine, but if I have a bunch of other applications running and I capture an image I get a Memory Warning, when this happens the image in the NSMutableArray is lost before I can save it. Is there a way to prevent iOS from clearing this NSMutableArray until I am done with it even if a memory error occurs? Thank you.

You will have a problem if you are creating your array at the controller -(void) loadView or -(void) viewDidLoad method.

After a memory warning, the controller might set the view property to nil , which will cause the method viewDidUnload of your controller to be called. I guess this is fine for you so far.

The problem is that after the viewDidUnload is called, if there is any attempt to access the controller view property (like by displaying the view after dismissing a modal, or by popping to the controller), the loadView and viewDidLoad method will be called again and, if you are setting the array in any of this two methods, you will lose your previous data because you will be setting the array again

EDIT:

This is not valid for iOS 5+ as the viewDidUnload method was deprecated and is never called in the UIViewController lifecycle

http://developer.apple.com/library/ios/#documentation/uikit/reference/UIViewController_Class/DeprecationAppendix/AppendixADeprecatedAPI.html#//apple_ref/occ/instm/UIViewController/viewDidUnload

When the method: - (void)didReceiveMemoryWarning is called, the viewDidUnload method is also called. Therefore, any code used in your viewDidUnload method would be called. So if you set the NSMutableArray to nil in the viewDidUnload method, the array would therefore remove all of it's objects, and be set to nil.

Hope that explains why!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM