Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
699 views
in Technique[技术] by (71.8m points)

iphone - does addSubview increment retain count?

I've tested it and it looks like it does. So my question is, does it ALWAYS increment the retain count.

So everytime I do something like this:

UIView *theView = [[[UIView alloc] initWithFrame:(CGRect)aFrame] autorelease];
[self.view addSubview:theView];

Am I actually leaking memory?

I have a global property @property (nonatomic, retain) UILabel *ingredientsTextLabel; which I instantiate in viewDidLoad with this code:

I just have the property named, theres no property for it in my header, so no getter and setter. In my viewDidLoad:

    ingredientsTextLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, ingredientsScrollView.frame.size.width, ingredientsScrollView.frame.size.height)];
    [ingredientsTextLabel setBackgroundColor:[UIColor clearColor]];
    [ingredientsTextLabel setFont:[UIFont fontWithName:@"Helvetica" size:18]];
    [ingredientsTextLabel setText:ingredientsText];
    [ingredientsTextLabel setNumberOfLines:0];
    [ingredientsTextLabel setLineBreakMode:UILineBreakModeWordWrap];
    NSLog(@"%i",[ingredientsTextLabel retainCount]); // here retain count is 1

    CGSize maxSize = CGSizeMake(ingredientsScrollView.frame.size.width, 9999);
    CGSize ingLabSize = [ingredientsText sizeWithFont:ingredientsTextLabel.font
                                    constrainedToSize:maxSize
                                        lineBreakMode:ingredientsTextLabel.lineBreakMode];

    [ingredientsTextLabel setFrame:CGRectMake(ingredientsTextLabel.frame.origin.x, ingredientsTextLabel.frame.origin.x, ingredientsTextLabel.frame.size.width, ingLabSize.height)];
    [ingredientsScrollView addSubview:ingredientsTextLabel];
    NSLog(@"%i",[ingredientsTextLabel retainCount]); // here retain count is 2!

Now I thought this would work and then in dealloc I can release ingredientsTextLabel, but the retain count is 2, so do I need to also release i after I addSubview as well? I didn't realise this happens! :(

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Yes, "addSubview" increases the retain count. This makes sense because the method stores the subview which should not be released/freed until the superview is also released. When the superview is release it also releases all its subviews.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...