How to delete UIViewController corectly?

2019-09-16 02:18发布

MyPlatesViewController* viewController = [[MyPlatesViewController alloc] initWithNibName:@"MyPlates" bundle:nil ];
[self.view addSubview:viewController.view];

then i delete my viewController

[self.view removeFromSuperview];

but leak instrument shows 20 MB memory

What is wrong ?

2条回答
啃猪蹄的小仙女
2楼-- · 2019-09-16 02:43

You called alloc so it's your responsibility to release it. Your code should look like this:

MyPlatesViewController* viewController = [[MyPlatesViewController alloc] initWithNibName:@"MyPlates" bundle:nil ];
[self.view addSubview:viewController.view];
[viewController release]

Note that your controller is retained by the view when you call addSubview and released when you call removeFromSuperview. So with your current code the retain count of viewController is still 1 after calling removeFromSuperview.

Additionally you should review objective-c memory manament here: http://developer.apple.com/library/mac/#documentation/cocoa/Conceptual/MemoryMgmt/Articles/mmRules.html

查看更多
SAY GOODBYE
3楼-- · 2019-09-16 03:09

You leaked the view controller object. After you remove the view from its superview, you need to release the controller as well.

Alternatively, you can do the following:

[self presentModalViewController:viewController animated:NO];
[viewController release];

Then, when dismissModalViewController is called, both the view and the view controller will be released properly.

查看更多
登录 后发表回答