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 {
UILa开发者_运维知识库bel *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:
- Create a subclass of UILabel for the default label type.
- 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.
You just need to autorelease your object before you return it:
- (UILabel *)defaultLabelWithFrame:(CGRect)frame
{
…
return [label autorelease];
}
Most methods in Cocoa will retain objects as needed, including addSubview:
. If no object uses (i.e. retains) the label, you don’t need to worry about it being leaked — it’s already been added to the autorelease pool and will be released automatically.
精彩评论