转自: http://www.cocoachina.com/ios/20150610/12093.html
首先了解下面三个知识:
1. __weak NSString *string_weak_ = nil; weak变量在它指向的对象被释放后,weak变量的值会被置为nil
2. 作用域
3. 变量在 = 号右边时,该变量会被retain一次,引用计数+1
4. 变量出了作用域时,会被release一次
5. 变量在autoreleasepool结束时,会被release一次
6. 执行了- (void)viewWillAppear:(BOOL)animated {}后,viewDidLoad中系统创建释放池X被销毁,其中的所有对象release一次。
下面是源码:
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
__weak NSString *string_weak_ = nil;
- (void)viewDidLoad {
[super viewDidLoad];
// 场景 1
// NSString *string = [NSString stringWithFormat:@"leichunfeng"];
// string_weak_ = string;
//
// 场景 2
// @autoreleasepool {
// NSString *string = [NSString stringWithFormat:@"leichunfeng"];
// string_weak_ = string;
// }
// 场景 3
NSString *string = nil;
@autoreleasepool {
string = [NSString stringWithFormat:@"leichunfeng"];
string_weak_ = string;
}
NSLog(@"string: %@", string_weak_);
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
NSLog(@"string: %@", string_weak_);
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
NSLog(@"string: %@", string_weak_);
}
@end
NSString *string = [NSString stringWithFormat:@"leichunfeng"]; 创建string引用计数 = 1,自动放入了系统的自动释放池X里面
string_weak_ = string; 被引用了一次,string引用计数 = 2
出了作用域后string引用计数 = 1
执行了- (void)viewWillAppear:(BOOL)animated {}后,viewDidLoad中系统创建释放池X被销毁,其中的所有对象release一次。string的引用计数= 0.所以结果如下
// 场景 1
2015-05-30 10:32:20.837 AutoreleasePool[33876:1448343] string: leichunfeng 此时 = 2
2015-05-30 10:32:20.838 AutoreleasePool[33876:1448343] string: leichunfeng 此时出作用域 -1
2015-05-30 10:32:20.845 AutoreleasePool[33876:1448343] string: (
null
) 此时释放池已经被销毁了
// 场景 2
2015-05-30 10:32:50.548 AutoreleasePool[33915:1448912] string: (
null
)
2015-05-30 10:32:50.549 AutoreleasePool[33915:1448912] string: (
null
)
2015-05-30 10:32:50.555 AutoreleasePool[33915:1448912] string: (
null
)
// 场景 3
2015-05-30 10:33:07.075 AutoreleasePool[33984:1449418] string: leichunfeng
2015-05-30 10:33:07.075 AutoreleasePool[33984:1449418] string: (
null
)
2015-05-30 10:33:07.094 AutoreleasePool[33984:1449418] string: (
null
)
|