0

大家好,我很难找到内存泄漏。当我解除分配它们时,我的所有保留计数 = 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];

}

某处,代码泄漏,我无法弄清楚我的生活在哪里。对此的任何帮助将不胜感激。

4

5 回答 5

3

使用仪器找到您的泄漏点。

问题是你还没有理解 Cocoa 的内存管理

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

你不应该自己打电话-deallocNSObject当引用计数达到 0 时调用它。

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

于 2009-10-08T16:38:20.847 回答
2

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

如果这没有帮助,请在 Instruments 中运行 Leaks 工具(Run->Run With Performance Tool->Leaks)。

于 2009-10-08T16:33:24.600 回答
0

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

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

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

于 2009-10-08T16:44:44.327 回答
0

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

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

永远不要打电话dealloc系统会为你做这件事。

不要release在同一个方法中两次调用同一个对象。您永远不知道在第一次调用后对象是否仍然存在。我很惊讶你没有得到过度释放的异常,更不用说泄漏了。

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

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

于 2009-10-08T16:49:38.047 回答
0

只是关于使用 [x retainCount] 来“帮助”识别内存问题的评论。正如我多次了解并尝试过的那样 - 这可能无法反映正确的情况。所以不要依赖这个值——不要使用它——它很可能会引起混淆。

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

于 2010-08-10T21:42:43.813 回答