目标c - 参考计数

时间:2012-05-22 11:57:31

标签: iphone objective-c ios reference-counting retaincount

直到五分钟我才确定我对Objective c引用计数的理解非常好,但是当我开始检查对象retainCount时,我很惊讶地看到了我看到的内容。

例如myViewController有一个UITableview:

.h文件

@interface RegularChatViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>
{
     UITableView *_tableView;
}
@property (nonatomic, retain) IBOutlet UITableView *tableView; 

.m文件

@synthesize tableView = _tableView;

- (void)loadView
{
    _tableView = [[UITableView alloc] init];  // STEP ONE
    NSLog(@"tableView retain count: %d",[_tableView retainCount]);

    self.tableView.frame = CGRectMake(0, 0, 320, tableHeight); // STEP TWO
    NSLog(@"tableView retain count: %d",[_tableView retainCount]);  

    [self.view addSubview:self.tableView]; // STEP THREE
    NSLog(@"tableView retain count: %d",[_tableView retainCount]); 
}

令我惊讶的是输入是:

tableView retain count: 1
tableView retain count: 2
tableView retain count: 3

显然,STEP ONE使用alloc

将保留计数增加1

我也知道STEP THREE使用addSubview

将保留计数增加1

但是在第二步中发生了什么?为什么它增加了保留计数?
是否与ARC有关?

5 个答案:

答案 0 :(得分:7)

根据retainCount方法的NSObject Protocol Reference上的Apple文档:

重要 此方法在调试内存管理问题时通常没有任何价值。因为任何数量的框架对象可能保留了一个对象以保存对它的引用,而同时自动释放池可能在对象上保留任意数量的延迟版本,所以您不太可能从此获取有用信息方法

答案 1 :(得分:2)

只要您与任何框架方法或功能进行交互retainCount方法就会变得完全无用,因为您不知道这些内容在黑匣子中的作用(它们是可以将您的对象添加到自动释放池或其他任何内容中,您不应该关心它。

使用retainCount调试内存管理问题总是一个坏主意。请参阅this answer了解更多原因以避免它。

答案 2 :(得分:2)

我在这里有一个方便的指南:When to use retainCount?

简而言之,retainCount很少意味着您的想法。在不知道如何实施UITableViewUIView的情况下,您无法知道保留计数应该是什么。我们甚至没有将自动释放考虑在内......

答案 3 :(得分:0)

第二步: - 通过使用自我。将调用tableView,tableview属性的getter(设置为retain)。 因此,您的财产被分配和保留两者,因此分别保留计数增加。

每当你必须分配一个保留属性时,你应该覆盖它的getter方法,这称为lazy instantiation。

最好在你的getter中分配你的tableview,例如

-(UITableView *) tableView
{
     if(!_tableView) {
          _tableView  =  [[UITableView alloc]init];
     }

    return _tableView;
}

答案 4 :(得分:0)

从getter返回self.tableView.frame时,

retainautoreleasetableView

相关问题