找到内存泄漏的麻烦

时间:2009-10-08 16:30:37

标签: iphone objective-c memory-leaks p2p dealloc

嘿大家,我找不到内存泄漏。所有关闭我的保留计数= 0当我解除它们但我仍然标记下面的代码泄漏:

- (GKSession *) peerPickerController:(GKPeerPickerController *)picker sessionForConnectionType:(GKPeerPickerConnectionType)type {
inSession = [[GKSession alloc] initWithSessionID:gameSessionID displayName:nil sessionMode:GKSessionModePeer];
printf( "insession alloc on Start: %i\n", [inSession retainCount] );
return inSession;

}

在取消对等选择器时,如果你没有找到任何人连接,我运行这个代码来摆脱与对等选择器有关的一切。

- (void)peerPickerControllerDidCancel:(GKPeerPickerController *)picker { 
picker.delegate = nil;
mpicker.delegate = nil;
inSession.delegate = nil;
gameSession.delegate = nil;

if(inSession != nil) {

    [self invalidateSession:inSession];
    [inSession release];
    inSession = nil;

}

[picker release];

picker = nil;
mpicker = nil;



[inSession release];


if(self.gameSession != nil) {
    [self invalidateSession:self.gameSession];
    [self.gameSession release];
    self.gameSession = nil;
}

[self.gameSession release];
self.gameLabel.hidden = NO;
self.gameState = pongStateStartGame;


[gameSession release];
[inSession release];

[inSession dealloc];
[gameSession dealloc];



[mpicker dealloc];

}

在某个地方,代码泄漏了,我无法弄清楚我的生活在哪里。任何对此的帮助都会非常感激。

5 个答案:

答案 0 :(得分:3)

使用Instruments查找您的泄密信息。

问题是你还没有理解Cocoa的memory management

[inSession dealloc];
[gameSession dealloc];
[mpicker dealloc];

从不必须自己致电-deallocNSObject在引用计数达到0时调用此方法。

尝试学习管理内存的正确方法。

答案 1 :(得分:2)

考虑运行Xcode 3.2的Build and Analyze(在Build菜单下)。这对于查找引用计数问题非常有帮助。

如果这样做无效,请运行仪器中的泄漏工具(运行 - >运行与性能工具 - >泄漏)。

答案 2 :(得分:0)

在将变量指针设置为nil之后尝试再次释放它将无济于事 - 它不会做任何事情。也不要调用dealloc。虽然技术上不违法,但

- (GKSession *) peerPickerController:(GKPeerPickerController *)picker sessionForConnectionType:(GKPeerPickerConnectionType)type

方法表示可能导致这种泄漏的风格。它创建一个新的GKSession并将其设置为实例变量并返回对它的引用。它不使用任何一个参数。创建实例变量或自动释放它并返回它。调用此方法的代码在哪里?调用者是否保留返回值?

答案 3 :(得分:0)

在第二段代码中,您[inSession release]两次,然后dealloc

对不起,这只是大约200种不同类型的错误。

永远不要致电dealloc系统会为您做到这一点。

不要在同一方法中对同一对象调用release两次。在第一次调用后,您永远不知道对象是否仍然存在。令我感到惊讶的是,你没有得到过度释放的例外情况,而不是泄密。

有关保留和释放的使用的快速说明,请参阅此question

有关更详细的解释(非常值得),请阅读有关该主题的Cocoa文档。

答案 4 :(得分:0)

关于使用[x retainCount]来“帮助”识别内存问题的评论。正如我在几次学习和尝试过的那样 - 这可能无法反映正确的情况。所以不要依赖这个值 - 不要使用它 - 它最有可能引起混淆。

其次,我一直在使用Apple代码(当然在示例中有效),然后“出乎意料”,这会导致我的代码出现问题(出现在LEAKS仪器中) - 没有“滥用它”当然。有时候我花了几个小时来找到奇怪行为的最奇怪的原因。例如,只需添加UINavigationControllerDelegate作为响应的协议,代码可能会突然泄漏 - 没有更改任何其他代码行!

相关问题