[英]Objective c - Reference counting
直到五分鍾我才確定我對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 3使用addSubview
將保留計數增加1
但是在第二步中發生了什么? 為什么它會增加保留計數???
ARC有什么關系?
根據關於retainCount
方法的NSObject協議參考的 Apple文檔:
重要 此方法在調試內存管理問題時通常沒有價值。 因為任何數量的框架對象可能保留了一個對象以保存對它的引用,而同時自動釋放池可能在對象上保留任意數量的延遲版本,所以您不太可能從此獲取有用信息方法。
一旦你與任何框架方法或函數進行交互, retainCount
方法就變得完全沒用了,因為你不知道這些東西在黑盒子里做了什么(他們可以把你的對象添加到自動釋放池或其他任何東西)你應該'關心它。
使用retainCount
來調試內存管理問題總是一個壞主意。 請參閱此答案 ,了解更多原因以避免它。
我在這里有一個方便的指南: 何時使用retainCount?
簡而言之,retainCount很少意味着你的想法。 在不知道如何實現UITableView
和UIView
的情況下,您無法知道保留計數應該是什么。 我們甚至沒有考慮自動釋放......
嗯,在第二步: - 使用自我。 將調用tableView,tableview屬性的getter(設置為retain)。 因此,您的財產被分配和保留,因此保留計數分別增加。
每當你必須分配一個保留屬性時,你應該覆蓋它的getter方法,這稱為lazy instantiation。
更好地在你的getter中分配你的tableview,例如
-(UITableView *) tableView
{
if(!_tableView) {
_tableView = [[UITableView alloc]init];
}
return _tableView;
}
從getter返回tableView
時, self.tableView.frame
將retain
並autorelease
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.