[置顶] viewcontroller生命周期及切换时方法调用的顺序

ViewController的生命周期

各方法执行流程如下:
init—>loadView—>viewDidLoad—>viewWillApper—>viewDidApper—>viewWillDisapper—>viewDidDisapper—>viewWillUnload->viewDidUnload—>dealloc

切换时,方法调用的顺序

其实写了这么久的代码,真没有注意过这个问题,到底是viewdidload先调用还是viewdiddisappear先调用呢。

现在写了一个小例子来测测:


有两个viewcontroller,分别为ViewController(后面简称A)和BViewController(后面简称B)

//ViewController.h


#import <UIKit/UIKit.h>

@interface ViewController : UIViewController


@end

//ViewController.m

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

-(void)viewDidAppear:(BOOL)animated
{
    NSLog(@"A- viewDidAppear");
}

-(void)viewWillAppear:(BOOL)animated
{
    NSLog(@"A- viewWillAppear");
}

-(void)viewWillDisappear:(BOOL)animated
{
    NSLog(@"A- viewWillDisappear");
}

-(void)viewDidDisappear:(BOOL)animated
{
    NSLog(@"A- viewDidDisappear");
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    NSLog(@"A- viewDidLoad");
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

//BViewController.h

#import <UIKit/UIKit.h>

@interface BViewController : UIViewController

@end

//BViewController.m

#import "BViewController.h"

@interface BViewController ()

@end

@implementation BViewController

-(void)viewDidAppear:(BOOL)animated
{
    NSLog(@"B- viewDidAppear");
}

-(void)viewWillAppear:(BOOL)animated
{
    NSLog(@"B- viewWillAppear");
}

-(void)viewWillDisappear:(BOOL)animated
{
    NSLog(@"B- viewWillDisappear");
}

-(void)viewDidDisappear:(BOOL)animated
{
    NSLog(@"B- viewDidDisappear");
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    NSLog(@"B- viewDidLoad");
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/* #pragma mark - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */

@end

启动app,首先出现A,运行结果如下:
2015-04-06 15:11:34.761 viewchange[729:25610] A- viewDidLoad
2015-04-06 15:11:34.762 viewchange[729:25610] A- viewWillAppear
2015-04-06 15:11:34.769 viewchange[729:25610] A- viewDidAppear
继续点击按钮A–>B,运行结果如下:
2015-04-06 15:12:15.670 viewchange[729:25610] B- viewDidLoad
2015-04-06 15:12:15.675 viewchange[729:25610] A- viewWillDisappear
2015-04-06 15:12:15.676 viewchange[729:25610] B- viewWillAppear
2015-04-06 15:12:16.182 viewchange[729:25610] B- viewDidAppear
2015-04-06 15:12:16.182 viewchange[729:25610] A- viewDidDisappear

清楚的知道这些运行顺序,让我更清楚在什么时候该做什么更合适。

你可能感兴趣的:(生命周期,调用,viewcontroller)