我试图更深入地了解保留释放。这是我的代码,然后我将发布代码运行的输出。我不确定为什么当为'self'调用dealloc时保留计数永远不会为零。
其次,当我为其分配内存时,为什么 self.testNumber 的保留计数为 2,我应该使用“弱”属性来代替测试编号吗?
代码:
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
_testNumber = [[NSNumber alloc] initWithInt:10];
testNumber = [[NSNumber alloc] initWithInt:102];
_testInt = 105;
self.testNumber = [[NSNumber alloc] initWithInt:101];
NSLog(@"self.testNumber retain count = %d",[self.testNumber retainCount]);
NSLog(@"self.label retain count = %d",[self.label retainCount]);
self.label.text = [NSString stringWithFormat:@"%d %d %d",_testNumber.integerValue,self.testNumber.integerValue,testNumber.integerValue ];
NSLog(@"self before release retain count = %d",[self retainCount]);
[self release];
NSLog(@"self after release retain count = %d",[self retainCount]);
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)dealloc {
NSLog(@"_label after before retain count = %d",[_label retainCount]);
[_label release];
NSLog(@"_label after release retain count = %d",[_label retainCount]);
[super dealloc];
}
输出:
2013-04-08 15:31:28.503 propertiesTest[5561:907] self.testNumber retain count = 2
2013-04-08 15:31:28.507 propertiesTest[5561:907] self.label retain count = 3
2013-04-08 15:31:28.509 propertiesTest[5561:907] self before release retain count = 3
2013-04-08 15:31:28.510 propertiesTest[5561:907] self after release retain count = 2
2013-04-08 15:31:28.532 propertiesTest[5561:907] _label after before retain count = 3
2013-04-08 15:31:28.534 propertiesTest[5561:907] _label after release retain count = 2