2012-03-13 68 views
3

我想通過在按UIButton時調用viewWithTag來重用標籤。代碼在第一次執行時看起來沒問題,但是由於第7行,執行代碼時會出現多次泄漏?從superview,alloc和addSubview中刪除標籤,而不是使用viewWithTag只是更好?viewWithTag和addSubview

1. UILabel *label = (UILabel *)[self.view viewWithTag:100]; 
2. if(label == nil) { 
3. label = [[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 20, 20)] autorelease]; 
4. label.tag = 100; 
5. } 
6. 
7. [self.view addSubview:label]; 

回答

5

將代碼[self.view addSubview:label];移到您的if塊內。當你的if條件爲false時,這意味着標籤已經是viewcontroller視圖層次結構的一部分,所以如果你像原來的代碼一樣再次添加它,它將被雙重保留。

UILabel *label = (UILabel *)[self.view viewWithTag:100]; 
if (!label) { 
    label = [[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 20, 20)] autorelease]; 
    label.tag = 100; 
    [self.view addSubview:label]; 
} 
+0

我會嘗試一下。我怎樣才能捕捉像這樣的內存泄漏? – apy 2012-03-13 23:32:02

+0

使用儀器查找潛在的泄漏。這裏是一個教程:http://www.raywenderlich.com/2696/how-to-debug-memory-leaks-with-xcode-and-instruments-tutorial – jonkroll 2012-03-13 23:45:23

+0

出於某種原因,儀器不認爲我早先的代碼有任何泄漏。 – apy 2012-03-14 15:24:27

0

如果您正在使用.xib或故事板,只需將它與IBOutlet鏈接即可。

如果您僅使用代碼,請嘗試將其另存爲私有變量。

+0

我以編程的方式創建我的視圖,所以我會有很多ivars來管理。 – apy 2012-03-13 23:30:23