Prody
Prody

Reputation: 5298

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. Is autoreleasing it OK?

Upvotes: 0

Views: 229

Answers (2)

CodeGrue
CodeGrue

Reputation: 5933

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.

Upvotes: 3

rein
rein

Reputation: 33445

Yes autoreleasing is exactly right here.

Upvotes: 10

Related Questions