場景1:
這是一道筆試題
image.png
我說打印
10
10
100
100
面試官非說我可能不太理解
block
岖研,最后一個不應該打印100
場景2:
一個vc上有 a b c 三個view,如果vc和a 相互強引用警检,那么vc在pop后孙援,b c會不會走dealloc
方法
我的理解是a b c vc都不會走dealloc方法,但面試官給我的說法是他們打印過扇雕,說 b c會走dealloc
方法拓售。
我說不走的理解是:
如果vc都不釋放,self.view也不會釋放镶奉,那么自然也不會移除self.view上的子控件abc础淤,所以這種場景下vc a b c 都不會走dealloc
方法崭放。
寫代碼驗證,我的理解是正確的值骇。
@import UIKit;
@interface ViewControllerA : UIViewController
@end
@interface ViewControllerB : UIViewController
@end
@interface A : UIView
@end
@interface B : UIView
@end
@interface C : UIView
@property(nonatomic) UIViewController *vc;
@end
@implementation ViewControllerA
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
[self.navigationController pushViewController:[ViewControllerB new] animated:YES];
}
@end
@implementation ViewControllerB
- (void)dealloc
{
NSLog(@"---%@---",@"ff");
}
+ (instancetype)new {
UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
return [sb instantiateViewControllerWithIdentifier:@"ViewControllerB"];
}
- (void)viewDidLoad {
[super viewDidLoad];
[self.view addSubview: [A new]];
[self.view addSubview: [B new]];
C *aC = [C new];
/// 這里view強引用 vc莹菱,就會導致 vc 不釋放
aC.vc = self;
[self.view addSubview: aC];
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
[self.navigationController popViewControllerAnimated:YES];
}
@end
@implementation A
- (void)dealloc
{
NSLog(@"---%@---",@"A---");
}
@end
@implementation B
- (void)dealloc
{
NSLog(@"---%@---",@"B---");
}
@end
@implementation C
- (void)dealloc
{
NSLog(@"---%@---",@"C---");
}
@end