开发者

Release UIViewController if available

Hey, I'm adding a UIViewcontroller as a subview of my current view. With something like that:

[self.view addSubview:viewcontroller.view];

The user can interact with that added viewcontroller so I can't just release it after I added it's view as my subview, right ?

So I would like to release it the dealloc methode and set it to nil in viewDidUnload when my master viewcontroller gets unloaded, right ?

The problem is, the viewcontoller I add as a subview is not added every time. So the question is, how can I ceck if the开发者_如何学运维 viewcontroller was added as subview and if so, release it.

Thx a lot ! Sebastian


You can check it like this:

if(viewController)     
{
 [viewController release];
 viewController=nil;
}

and yes u need to put this in your dealloc method.


If you read correctly your code:

[self.view addSubview:viewcontroller.view];

it is not the controller which is being added as a subview, rather the view it manages.

This is an important point, since it means that the controller itself does not get retained. What is retained is the view.

So you can simply go on releasing your viewController in -dealloc as usual:

 -(void)dealloc {
     [viewController release]; viewController = nil;
     ...
 }

and in your viewController's dealloc you will need to release the managed view, if you allocated it manually (or wherever it makes sense for your controller to release its view, if necessary).

On the other hand, whenever your superview is deallocated, then also the view you added as a subview will be released (as per Apple spec of addSubview behavior). So nothing to worry about here. Just release the viewController properly (and make that the view controller manages correctly tis own view).

One more note: you should not release your view controller in viewDidUnload.


In some open source code that I used to contribute to, we had a macro called RELEASE_TO_NIL which did exactly this.

#define RELEASE_TO_NIL(obj) if(obj != nil) { [obj release]; obj = nil; }

You would use it like this:

RELEASE_TO_NIL(viewController);

Simple as that.


Just add an tag to viewController.view and test if self.view contains that tag.

UIView *testView = [self.view viewWithTag:yourTag];
if(testView!=nil){
   doStuff;
}


According to the Apple docs, a UIViewController instance should manage a view that fills the whole screen. If your view does not fill the screen, you could either subclass UIView to handle delegation or make the superview work as a delegate.

Also, the subviews of a view are contained in an instance of NSArray, do [myView subviews] to return this property. Ask the returned array if it contains the subview in question and you can release accordingly.

But, without knowing more, it does sound like you need to rethink how you're setting all this up.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜