简体   繁体   English

UIViewController保留计数问题

[英]UIViewController retain count problem

I am creating a new UIViewController with the below code 我用下面的代码创建一个新的UIViewController

GameViewController *temp = [[GameViewController alloc] initWithNibName:@"GameViewController" bundle:nil];
NSLog(@"retain count%d", [temp retainCount]);
temp.backgroundMusic = backgroundMusic;
self.gameView = temp;
[temp release];     
[self presentModalViewController:gameView animated:YES];                
[gameView release];

but when I look at retain counts, my temp view controller returns 4. 但是当我查看保留计数时,我的临时视图控制器返回4。

How this is possible?? 这怎么可能? Because it is 4, when I dismiss the view controller I cant remove it from memory and my game is going on playing. 因为它是4,所以当我关闭视图控制器时,无法将其从内存中删除,并且我的游戏还在继续进行。 (I can see the effects of AI playing). (我可以看到AI播放的效果)。

Never use retainCount, it does not work the way you think it does. 永远不要使用retainCount,它不会像您认为的那样起作用。

If you need to see where retains, releases and autoreleases occur for an object use instruments: 如果需要查看对象的保留,释放和自动释放位置,请使用工具:

Run in instruments, in Allocations set "Record reference counts" on on (you have to stop recording to set the option). 在乐器中运行,在分配中将“记录参考计数”设置为开(必须停止记录才能设置该选项)。 Cause the picker to run, stop recording, search for there ivar (datePickerView), drill down and you will be able to see where all retains, releases and autoreleases occurred. 使选择器运行,停止记录,在其中搜索ivar(datePickerView),向下钻取,您将能够看到发生了所有保留,释放和自动释放的位置。

屏幕截图示例

"You should never use retainCount ". “您永远不要使用retainCount ”。 Here is a very good description, why to not: stackoverflow 这是一个很好的描述,为什么不这样做: stackoverflow

I advise you never using retainCount because it usually gives false information about the actual retaincount of your object!!!! 我建议您不要使用keepCount,因为它通常会提供有关对象的实际keepcount的错误信息!

Just follow the appropiate memory management practices!!!! 只需遵循适当的内存管理惯例即可!!!! It's very simple really, just follow the NARC principle, release only the objects that have these words: New Alloc Retain Copy. 确实非常简单,只需遵循NARC原则,仅释放具有以下单词的对象:New Alloc Retain Copy。 NARC! NARC! :) :)

I strongly advise you using the memory leaks tool from instruments that tells you which objects were not released and which objects where released and you are trying to access. 我强烈建议您使用仪器中的内存泄漏工具,该工具会告诉您哪些对象尚未释放,哪些对象已释放,您正尝试访问。

In GameViewController have you released your background music as 在GameViewController中,您是否将背景音乐发布为

- (void)viewDidLoad{
   //Other nils
   self.backgroundMusic = nil;
}
- (void)dealloc{
    //Other releases
    [backgroundMusic release];
    [super dealloc];
}

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

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