Cocoa-Touch: memory management
I'm customizing a UIPickerView's rows, so I'm implementing the viewForRow method in it's delegate as follows:
- (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;
}
}
I'm new to Obj-C.
Since I'm aloc/initing l, I'm supposed to also release it according to the memory management guide. However I need to also return it. I开发者_StackOverflows autoreleasing it OK?
Yes autoreleasing is exactly right here.
I think the convention is to autorelease it in the alloc statement:
UILabel *l = [[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 300, 44)] autorelease];
Since you need the object to exist after the method exits, you have no choice but to use autorelease. Typically, you need to make sure in the calling method that you retain a copy, or it could be released on you randomly. In this case, the pickerView does this for you, so no worries.
精彩评论