[问题] weak 属性release时机

楼主: huangcooly (弱小豪)   2017-10-03 17:38:07
最近做了一些尝试
遇到一个问题
我在ViewController中有两个property为
@property (weak, nonatomic) UKTextField *myTextField;
@property (weak, nonatomic) Person *person;
UKTextField为继承UITextField的类别
Person为自己定义的类别
两个类别我都有覆写dealloc的方法
让两个物件被回收时可以显示Log
测试如下
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(@"viewDidLoad Start");
//Assigning retained object to weak variable;
//object will be released after assignment
myTextField = [[UKTextField alloc] init];
//Assigning retained object to weak variable;
//object will be released after assignment
person = [Person new];
}
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
NSLog(@"viewWillAppear Start");
}
-(void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
NSLog(@"viewDidAppear Start");
}
Log内容出现顺序如下
1.viewDidLoad Start
2.Person Dealloc
3.viewWillAppear Start
4.UKTextField dealloc
5.viewDidAppear Start
问题:
将UKTextField与Person皆设定为weak
就ARC来说当weak的物件应该再被指派完之后应该在viewDidLoad就会被回收了
但为什么UKTextField会在viewWillAppear才会被回收呢??
作者: darktt (小朱)   2017-10-03 19:06:00
release是从class的变量开始,直到变量全部release完了,class本体才行release
作者: yuanruo (罪を憎んで人を憎まず)   2017-10-03 19:55:00
用weak初始化对像,为了优化其实底层是调用class method等同于你初始完后它会被加到一个autoreleasePool里autoreleasePool 在viewDidload返回时,还没drain它被延迟到willAppear 到didAppear中某个方法被drain详细下断点自己去追stackTree 关键字AutoreleasePoolPage或是你可以把code编成C++ 直接看源码

Links booklink

Contact Us: admin [ a t ] ucptt.com