Creating UIButton using helper method

Posted by ddawber on Stack Overflow See other posts from Stack Overflow or by ddawber
Published on 2010-12-31T22:13:18Z Indexed on 2011/01/01 7:53 UTC
Read the original article Hit count: 294

Filed under:
|
|
|
|

I have a subclass of UITableView and in it I want to generate number of labels that share the same properties (font, textColor, backgroundColor, etc.).

I decided the easiest way to achieve this would be to create a helper method which creates the label with some common properties set:

- (UILabel *)defaultLabelWithFrame:(CGRect)frame {
    UILabel *label = [[UILabel alloc] initWithFrame:frame];
    label.font = [UIFont fontWithName:@"Helvetica" size:14];
    label.textColor = [UIColor colorWithWhite:128.0/255.0 alpha:1.0];
    label.backgroundColor = [UIColor clearColor];

    return label;
}

I use the method like this:

UILabel *someLabel = [self defaultLabelWithFrame:CGRectMake(0,0,100,100)];
[self addSubview:someLabel];
[someLabel release];

My concern here is that when creating the label in the method it is retained, but when I then assign it to someLabel, it is retained again and I have no way of releasing the memory when created in the method.

What would be best the best approach here?

I fee like I have two options:

  1. Create a subclass of UILabel for the default label type.
  2. Create an NSMutableArray called defaultLabels and store the labels in this:
- (UILabel *)defaultLabelWithFrame:(CGRect)frame {
    UILabel *label = [[UILabel alloc] initWithFrame:frame];
    label.font = [UIFont fontWithName:@"Helvetica" size:14];
    label.textColor = [UIColor colorWithWhite:128.0/255.0 alpha:1.0];
    label.backgroundColor = [UIColor clearColor];

    [defaultLabels addObject:label];
    [labels release]; //I can release here
    return [defaultLabels lastObject]; //I can release defaultLabels when done
}

I appreciate your thoughts. Cheers.

© Stack Overflow or respective owner

Related posts about iphone

Related posts about objective-c