------------------------------------------------------------------------------------------------------------------------------------------------
一. 有一次面试问到:从VC1 推到VC2会不会调用dealloc呢?答案是不会
而从VC2 dismiss 会调VC2的dealloc
不会调用VC1的dealloc方法 有代码为证:
#import "ViewController.h"
#import "ViewController2.h"
@interface ViewController () @end @implementation ViewController - (void)dealloc
{
NSLog(@"ViewController dealloc");
} - (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
} - (IBAction)goVC2:(id)sender {
ViewController2 *vc2 = [ViewController2 new];
[self presentViewController:vc2 animated:YES completion:^{ }]; } @end
#import "ViewController2.h" @interface ViewController2 () @end @implementation ViewController2 - (void)dealloc
{
NSLog(@"ViewController2 dealloc");
} - (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
二. ViewController中被加入了定时器,而没有及时的invalidate ,会怎样?
#import "ViewController.h"
#import "ViewController2.h"
@interface ViewController ()
{
NSTimer *timer;
}
@end @implementation ViewController - (void)dealloc
{
NSLog(@"ViewController dealloc %@",self);
} - (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
timer = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(updateTime:) userInfo:nil repeats:YES];
} -(void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
[timer invalidate];
} -(void)updateTime:(id)sender
{ NSLog(@"ViewController updateTime");
} - (IBAction)goVC2:(id)sender {
ViewController2 *vc2 = [ViewController2 new];
[self presentViewController:vc2 animated:YES completion:^{ }]; } @end
没调 [timer invalidate]; 打印
-- ::04.608616+ YiJTApp[:] ViewController updateTime
-- ::07.608558+ YiJTApp[:] ViewController updateTime
-- ::10.607419+ YiJTApp[:] ViewController updateTime
-- ::13.608551+ YiJTApp[:] ViewController updateTime
-- ::16.608406+ YiJTApp[:] ViewController updateTime
-- ::19.608554+ YiJTApp[:] ViewController updateTime
-- ::22.608535+ YiJTApp[:] ViewController updateTime
-- ::25.409616+ YiJTApp[:] ViewController2 dealloc
-- ::25.607751+ YiJTApp[:] ViewController updateTime
-- ::28.608624+ YiJTApp[:] ViewController updateTime
-- ::31.607510+ YiJTApp[:] ViewController updateTime
调 [timer invalidate]; 打印
-- ::12.271080+ YiJTApp[:] ViewController updateTime
-- ::23.268043+ YiJTApp[:] ViewController2 dealloc
不管是有定时器,或者被代理,block强引用。VC1都不会调delloc方法。