How to implement didReceiveMemoryWarning?

前端 未结 6 1873
一生所求
一生所求 2020-11-30 19:38

I have developed a simple location aware iPhone application which is functionally working very well to our expectations except in the low memory condition of the phone .

6条回答
  •  再見小時候
    2020-11-30 20:20

    On iOS 5 and earlier.

    When controller receive a memory warning, didReceiveMemoryWarning will be called. At that time, if controller's view is not in the view hierarchy, the view will be set to nil and viewDidUnload will automaticly invoked. So the things we must do in viewDidUnload is releasing sub view created in viewDidLoad or created from Nib. Like this:

    - (void)viewDidUnload
    {
        self.subView = nil;
        self.subViewFromNib = nil;
    }
    
    - (void)didReceiveMemoryWarning
    {
        self.someDataCanBeRecreatedEasily = nil;
        [super didReceiveMemoryWarning];
    }
    

    On iOS6.

    The controller doesn't automaticly release the view when receive a memory warning. So the viewDidUnload never be called. But we still need to release our view (including sub view) when a memry warning happens. Like this.

    - (void)didReceiveMemoryWarning
    {
        if ([self isViewLoaded] && [self.view window] == nil) {
            self.view = nil;
            self.subView = nil;
            self.subViewFromNib = nil;
        }
        self.someDataCanBeRecreatedEasily = nil;
        [super didReceiveMemoryWarning];
    }
    

    Note that we don't call [self view] before we know the view is loaded. cause the this method will automaticly load view if the view is not loaded.

    Note that we can release the view just when the view is not added to a window.

提交回复
热议问题