2009-10-08 57 views
0

我定製一個UIPickerView的行,所以我實現它的委託viewForRow方法如下:可可觸摸:內存管理

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view { 
    if (view) { 
     return view; 
    } else { 
     NSString *s = [datePickerValues objectAtIndex:row]; 

     UILabel *l = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 300, 44)]; 
     l.text = s; 
     l.font = [UIFont boldSystemFontOfSize:18]; 
     l.textAlignment = UITextAlignmentCenter; 
     l.backgroundColor = [UIColor purpleColor]; 

     [l autorelease]; 
     return l; 
    }  
} 

我是新來的OBJ-C。

因爲我是aloc/initing l,所以我應該根據內存管理指南發佈它。但是我也需要返回它。是autoreleasing它行嗎?

+0

你可以使用return [l autorelease]從你的代碼中刪除一行; – pxl 2009-10-08 18:28:12

+0

要麼作爲alloc/init的一部分,要麼作爲autorelease的一部分 – Lounges 2009-10-08 18:41:18

回答

10

是的autoreleasing就在這裏。

+0

事實上,正是這個用例是創造'NSAutoreleasePool'的動機。 – 2009-10-08 19:00:49

3

我認爲約定是自動釋放它的頁頭聲明:

UILabel *l = [[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 300, 44)] autorelease]; 

既然你所需要的對象的方法退出後存在,你沒有選擇,只能使用自動釋放。通常情況下,您需要確保在調用方法中保留副本,或者隨機發布。在這種情況下,pickerView爲你做這個,所以不用擔心。