gpt4 book ai didi

objective-c - initWithContentRect 和 setContentView 中的内存泄漏

转载 作者:行者123 更新时间:2023-12-03 16:46:21 26 4
gpt4 key购买 nike

在我的应用程序中,我正在创建一个窗口并设置内容 View 。检查器向我展示了一些内存泄漏。

setContentView:中,我认为它释放了以前的NSView

我的代码如下:

//contentrect is NSRect which is already initialized.
//stylemask is NSUInteger which is also initialized.
//window_ is of NSWindow type.
window_ = [NSWindow alloc];

//Here, I am getting memory leak.
window_ = [window_ initWithContentRect:contentrect styleMask:stylemask
backing:NSBackingStoreBuffered defer:NO];

//Set window delegate to receive close notication.
[window_ setDelegate:delegate_];

//I believe this is the behavior is by default.
//[window_ setReleasedWhenClosed:YES];

//Setting the windows title.
[window_ setTitle:title_];

//Setting the window frame screenrect which is also initialized.
[window_ setFrame:screenrect display:YES animate:YES];

//MyView is inherited from NSView.

//Set MyView instead of default NSView.
//Set as it have same content rectangle.

contentrect = [[window_ contentView] frame];
//Allocate MyView.
MyView * view = [[MyView alloc] initWithFrame:contentrect];


[window_ setContentView:view];


[rWindow orderFront:nil];

编辑:我在调用的 setContentView 中没有出现内存泄漏,但在内部调用为 initWithContentRectsetContentView 中没有出现内存泄漏。

最佳答案

您必须平衡保留/释放计数

你必须在某个地方释放window_,其中一个地方将在dealloc

- (void)dealloc
{
[window_ release]; window_ = nil;
// other releases
[super dealloc];
}

在不同的行中alloc init是一个坏主意

同样,您必须在 setContentView 之后添加 [view release]; 来释放您的view

自动释放

MyView * view = [[[MyView alloc] initWithFrame:contentrect] autorelease];

如果你不知道 Objective-C 中的管理是如何工作的,你最好先切换到 ARC 并详细了解它是如何工作的。

关于objective-c - initWithContentRect 和 setContentView 中的内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20233814/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com