简体   繁体   English

Objective-C内存在addSubview上泄漏

[英]Objective-C Memory Leak on addSubview

The leak instruments warn me about a memory leak related to this part of code: 泄漏仪器警告我与这部分代码相关的内存泄漏:

[self.contview addSubview:nav.view];

Here are how I manage the view: 以下是我管理视图的方式:

    [nav.view removeFromSuperview];
    self.nav = [[[destinationClass alloc] initWithNibName:pagename bundle:nil] autorelease];
   [self.contview addSubview:nav.view];

Is it normal that the self.nav has a retainCount of 2 just after been allocated?Could this be related to the memory leak? self.nav刚刚分配后的retainCount是2是否正常?这可能与内存泄漏有关吗?

I'm very new to the memory management can someone give me some help? 我对记忆管理很新,有人可以给我一些帮助吗?

Many Thanks 非常感谢

Assuming nav is a strong (retain) property, it retains the view controller you are assigning here: 假设nav是一个强(保留)属性,它会保留您在此处指定的视图控制器:

self.nav = [[[destinationClass alloc] initWithNibName:pagename bundle:nil] autorelease];

effectively, the retain count after this line of code is 1; 实际上,这行代码后的保留计数为1; +2 for alloc and retain and -1 for autorelease . 对于allocretain +2,对于autorelease retain -1。 Generally you should never use retainCount method to determine the actual retain count of the object, maybe this answer will give you more insight why. 通常你永远不应该使用retainCount方法来确定对象的实际保留计数,也许这个答案会让你更深入地了解原因。 Every alloc , retain or copy call should be matched with a release or autorelease call. 每个allocretaincopy调用都应该与releaseautorelease调用匹配。 You should add a matching release call in dealloc method of your class 您应该在类的dealloc方法中添加匹配的版本调用

-(void) dealloc {
    [_nav release];
    _nav = nil;
    [super dealloc];
}

Don't use manual memory management, use ARC, it will make your life much easier :) 不要使用手动内存管理,使用ARC,它会让你的生活更轻松:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM