标签:
如果你使用过MRR,autorelease这个关键字应该是太熟悉了,每次在我们生成一个新的对象返回时,都需要向这个对象发送autorelease消息,目的是为了延时释放创建的对象。那到底是在什么时候,这个对象会被释放呢?有什么方法可以更快的释放一个autorelease对象呢?
咱们先来看一个现象:
@property (weak, nonatomic) NSString *weakString; - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. NSString *hello = [[NSString alloc] initWithCString:"it will be released at the end of current runloop" encoding:NSUTF8StringEncoding]; self.weakString = hello; NSLog(@"%@ - %@", self.weakString, NSStringFromSelector(_cmd)); } - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; NSLog(@"%@ - %@", self.weakString, NSStringFromSelector(_cmd)); } - (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; NSLog(@"%@ - %@", self.weakString, NSStringFromSelector(_cmd)); dispatch_async(dispatch_get_main_queue(), ^{ NSLog(@"-2--%@ - %@", self.weakString, NSStringFromSelector(_cmd)); }); }
我们创建了一个viewDidLoad方法中创建了一个weak指针指向一个字符串,当代码执行到viewWillAppear:和viewDidAppear:时,我们依然可以打印出weak指针指向的字符串,当在viewDidAppear:中在下一个runloop中执行打印操作时,weak指针就指向nil了,Why ?
我们完全可以这么翻译这条语句到MRR:self.weakString = hello
self.weakString = [[hello retain] autorelease];
这样看,我们是不是可以猜测autorelease的对象是在当前的runloop结束后就被释放掉了呢?
我们要厘清的事情可能有以下几个方面:
1)autorelease pool
标签:
原文地址:http://www.cnblogs.com/goodyboy6/p/4462968.html