When to release an alloc. textField?

Discussion in 'iOS Programming' started by yrvaken2, Jan 4, 2009.

  1. macrumors newbie

    Joined:
    Sep 15, 2008
    #1
    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

    Code:
    @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];
        }
    }
    
    @end
    
     
  2. Moderator

    dejo

    Staff Member

    Joined:
    Sep 2, 2004
    Location:
    The Centennial State
    #2
    Do you have textField set up as a property in the .h? If so, how?
     
  3. thread starter macrumors newbie

    Joined:
    Sep 15, 2008
    #3
    Code:
    @interface EditableCell : UITableViewCell {
        UITextField *textField;
    }	
    @property (nonatomic, retain) UITextField *textField;
    
     
  4. Moderator

    dejo

    Staff Member

    Joined:
    Sep 2, 2004
    Location:
    The Centennial State
    #4
    Then you should be fine releasing it in the dealloc.
     
  5. thread starter macrumors newbie

    Joined:
    Sep 15, 2008
  6. Moderator

    dejo

    Staff Member

    Joined:
    Sep 2, 2004
    Location:
    The Centennial State
    #6
    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.
     

Share This Page