user hhh
user hhh

Reputation: 189

self removeFromSuperView don't release self?

I dynamically add a subview to another uiview;

in the subview ,click a button to go back by the following method:

[self removeFromSuperView ];

but after manny times added subview and removed it,my app could crash ,the log said it was killed .

I found that calling [self removeFromSuperView] didn't release self. So what's the best methods to releas it?

Upvotes: 3

Views: 4122

Answers (3)

Magic Bullet Dave
Magic Bullet Dave

Reputation: 9076

If you are retaining the UIView on creation (or adding it to an array) the retain count will increase. For example:

// Retain count is 1
UIView *myView = [[UIView alloc] initWithFrame:myFrame];

// Retain count is 2
[myParentView addSubview:myView];

// Retain count is 1 again
[myView removeFromSuperView];

In the above example you can autorelease the view if it is immediately added as a subView or release it in your dealloc if it is an iVar.

EDIT: (other reasons your view could be retained)

// Retain count +1
[myArray addObject:myView];

// Retained in the setter created by the @synthesize directive
@property(nonatomic, retain) UIView *myView;

Anything else that states in the documentation that the property is retained.

You should also be careful of creating objects in the loadView method of a VC, if you do make sure you release them, as they will be created again when the loadView is called. This will happen if you VC's view is unloaded and then reloaded.

Upvotes: 4

neal
neal

Reputation: 106

u should release at first. counterpart of "alloc" is "release", and counterpart of "addSubview" is "removeFromSuperView":keep those balance.

add view:

UIView *myView = [[UIView alloc] initWithFrame:myFrame];
[myParentView addSubview:myView];
[myView release];

remove view (the view will clear up in memory after removeFromSuperView):

[myView removeFromSuperView];

Upvotes: 2

Denis Mikhaylov
Denis Mikhaylov

Reputation: 2045

Looks like you are adding retained view as a subview. Its parent view retains it once again. So when you cell [self removeFromSuperView]; it gets release message from superView, but still have to be releasd by creator.

Upvotes: 0

Related Questions