views:

60

answers:

2

Hello all, I wanted to clarify something:

I.e when I add a UIVIEW To i.e another UIVIEW programatically.

i.e [theview addsubview:thechildview];

I need to release thechildview because theview increments the retain count.

Right?

So basically if I have a loop and I am using that loop to initialise subviews and add the subviews to a view:

for(int i=0;i<10;i++){

    UIView *child = [UIview alloc]init.....
    [parent addSubview:child];
    [child release];
}

I still need to release the child right ? So that would mean the child view still has a retain count of 1 right ?

The thing is whenever I call the release on the child after adding , the child gets deallocated after a while.

Can you guys confirm am doing the right thing by releasing the child after it is added ?

thanks.

+3  A: 

You should release it somewhere, correct. You can hold on it and release it later, but it is your responsibility to do it somewhen.

The parent view will retain/release its childs on its own. So if the parent view gets dealloc'ed, it will release its child views.

If a child view is removed from its superview, it will also be released.

Eiko
Thanks for the confirmation.
Please accept this answer if it answers your question :)
Rengers
+2  A: 

I need to release thechildview because theview increments the retain count.

Right

Wrong.

You need to release theChildView if you own it and if you have finished using it. Whether theview chooses to retain it or not is completely irrelevant.

So if we look at your loop

for(int i=0;i<10;i++){

    UIView *child = [UIview alloc]init.....
    [parent addSubview:child];
    [child release];
}

the code is correct because at the beginning of the loop block you alloc the child which means you own it and at the end of the loop it is about to go out of scope which means you no longer need it so you must release (or autorelease) it.

What happens in between is totally irrelevant and you should not assume anything about what any particular method on another object does (except that it adheres to the Memory Management Rules).

I still need to release the child right ? So that would mean the child view still has a retain count of 1 right ?

You cannot assume anything about the retain count. parent might cause the object to be retained more than once if it hands it off to other objects. It might choose to copy it instead of retaining it. If it doesn't need to keep a reference it might not retain it at all.

Can you guys confirm am doing the right thing by releasing the child after it is added ?

No, you are doing the right thing by releasing it when you have finished using it.

JeremyP
Ye, depending on retain count isn't the way to go. If I am going to be using those child views somewhere else in the same class, I might not need to release it now.