UIViewController加载和卸载过程

加载过程:

一般情况下调用 init方法或者调用initWithNibName方法实例化UIViewController, 不管调用哪个方法都为调用initWithNibName(方法定义如下)

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil

接着会调用loadView方法来生成UIViewController.view

- (void)loadView

然后调用 viewDidLoad方法

- (void)viewDidLoad

如果loadView不能生成UIViewController.view系统将会反复调用loadView及viewDidLoad方法, 并且最终调用[super loadView] 方法返回UIViewController.view

然后依次调用如下2个方法, 这2个方法也十分重要, 在UINavigationController的POP操作后有时将要显示的UIViewController中的View并没有释放(也有可能释放掉) , UIViewController将不会调用上面的三个方法(initWithNibName,loadView,viewDidLoad) 而会调用下面这2个方法

- (void)viewWillAppear:(BOOL)animated;

- (void)viewDidAppear:(BOOL)animated;

在iOS5.0中还添加了2个函数:

- (void)viewWillLayoutSubviews ;

- (void)viewDidLayoutSubviews;

另外如果你这样写:

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{

self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];

if (self) {

UIView *view = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];

self.view = view;

[view release];

// Custom initialization

NSLog(@”initWithNibName”);

}

return self;

}

那么loadView和viewDidLoad 方法将不会被调用

卸载过程

- (void)viewWillDisappear:(BOOL)animated;

- (void)viewDidDisappear:(BOOL)animated;

- (void)viewWillUnload;//iOS5.0添加

- (void)viewDidUnload;

- (void)dealloc;

PS: 当程序收到内存不足的警告后, 程序内存中的所有的UIViewController都将会收到didReceiveMemoryWarning调用消息. 目的是将当前不显示的UIViewController中的view释放掉(不会调用UIViewController的dealloc方法), 所以当该UIViewController再次显示的时候又要生成一次, 此时它会调用loadView-> viewDidLoad ->viewWillAppear等, 这时最容易造成内存泄漏!

- (void)didReceiveMemoryWarning;

- (void)viewWillUnload;//iOS5.0添加

- (void)viewDidUnload;

另附一篇很有价值的文章:

from:http://stackoverflow.com/questions/5069978/didreceivememorywarning-viewdidunload-and-dealloc

Some corrections and suggestions:

  • didReceiveMemoryWarning practices

As you said, the controller’s default implementation of didReceiveMemoryWarning releases its view if it is ‘safe to do so’. While it’s not clear from Apple’s documents what ‘safe to do so’ means, it is generally recognized as it has no superview (thus there is no way that the view is currently visible), and itsloadView method can rebuild the entire view without problems.

转载自 : http://willonboy.tk/?p=518

你可能感兴趣的:(apple,UIView,ios5)