View Full Version : When to release an alloc. textField?

Jan 4, 2009, 05:51 AM
I do not really understand this with memory management. In this case when the TextField is Alloc. Do I have to set an Autorelease on it or will it be enough to have the release in "dealloc"?

Thanks Anders

@implementation EditableCell

@synthesize textField;

- (id)initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
if (self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) {
// Set the frame to CGRectZero as it will be reset in layoutSubviews
textField = [[UITextField alloc] initWithFrame:CGRectZero];
textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
textField.font = [UIFont systemFontOfSize:16.0];
textField.textColor = [UIColor blackColor];
[self addSubview:textField];
return self;

- (void)dealloc {
// Release allocated resources.
[textField release];
[super dealloc];

- (void)layoutSubviews {
// Place the subviews appropriately.
textField.frame = CGRectInset(self.contentView.bounds, 20, 0);

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
// Update text color so that it matches expected selection behavior.
if (selected) {
textField.textColor = [UIColor whiteColor];
} else {
textField.textColor = [UIColor darkGrayColor];


Jan 4, 2009, 01:10 PM
Do you have textField set up as a property in the .h? If so, how?

Jan 4, 2009, 05:26 PM
@interface EditableCell : UITableViewCell {
UITextField *textField;
@property (nonatomic, retain) UITextField *textField;

Jan 4, 2009, 05:49 PM
Then you should be fine releasing it in the dealloc.

Jan 5, 2009, 12:33 PM
Do you mind explain why?

Jan 5, 2009, 12:40 PM
When you alloc the UITextField, you are assigning it immediately to the textfield property, which has a retain directive. Therefore, as long as the class is instantiated, the memory for this property will be retained. When the class gets de-instantiated, the dealloc method will be called and then the memory for the textField will be released (via the [textField release]) since it is no longer necessary to retain it.