NSURL 在创建后几乎立即被释放(目标 C)

发布于 2024-12-06 04:08:39 字数 528 浏览 0 评论 0原文

在我的代码中,我在应用程序委托的头文件中创建了一个名为 fromURL 的 NSURL 对象。

NSURL *fromURL;

这是我设置它的时候:

NSOpenPanel* openDlg = [NSOpenPanel openPanel];
[openDlg setCanChooseFiles:NO];
[openDlg setCanChooseDirectories:YES];
[openDlg setCanCreateDirectories:YES];
[openDlg setPrompt:@"Select"];
if ([openDlg runModal] == NSOKButton )
{
    fromURL = [openDlg URL];
}

这是我的问题。当我设置它时,我可以在创建它后立即对其设置进行 NSLog,但下次我尝试从中获取信息时,它会显示 EXC_BAD_ACCESS。我打开了僵尸,在我设置它之后它几乎立即变成了僵尸。

这怎么会立即被释放?!?

In my code I create an NSURL object called fromURL in the header file of my application delegate.

NSURL *fromURL;

Here is when I set it:

NSOpenPanel* openDlg = [NSOpenPanel openPanel];
[openDlg setCanChooseFiles:NO];
[openDlg setCanChooseDirectories:YES];
[openDlg setCanCreateDirectories:YES];
[openDlg setPrompt:@"Select"];
if ([openDlg runModal] == NSOKButton )
{
    fromURL = [openDlg URL];
}

Here's my problem. When I set it I can NSLog what it is set to immediately after it is created but the next time I try to get the information from it it says EXC_BAD_ACCESS. I have turned on zombies and it becomes a zombie almost immediately after I have set it.

How is this just getting immediately deallocated?!?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

浪荡不羁 2024-12-13 04:08:39

听起来你需要阅读 内存管理编程指南

这里发生的事情是,您的 fromURL 变量是一个 ivar(至少,我假设它是一个 ivar,您可能已将其设为全局变量)。您在方法中分配给它。但是您没有处理内存管理,因此当控制权返回到运行循环并且自动释放池耗尽时,您的 fromURL ivar 最终会指向已释放的对象。您需要根据需要保留和释放。对于这个特定的方法,我可能会使用

if ([openDlg runModal == NSOKButton)
{
    [fromURL release];
    fromURL = [[openDlg URL] retain];
}

并且也不要忘记在您的 -dealloc 方法中释放 fromURL

如果您为 fromURL 定义一个属性,则可以简化一点,就像这样,

@property (nonatomic, retain) NSURL *fromURL;

您可以使用这种方式

self.fromURL = [openDlg URL];

,而不必担心保留/释放,除了在 -dealloc 中,其中您仍然需要[fromURL release]

Sounds like you need to read the Memory Management Programming Guide.

What's going on here is that your fromURL variable is an ivar (at least, I assume it's an ivar, you might have made it a global variable instead). You're assigning to it in your method. But you're not dealing with memory management, so when control returns to the run loop and the autorelease pool is drained, your fromURL ivar ends up pointing at a released object. You need to retain and release as appropriate. For this particular method I might use

if ([openDlg runModal == NSOKButton)
{
    [fromURL release];
    fromURL = [[openDlg URL] retain];
}

And don't forget to release fromURL in your -dealloc method either.

This can be simplified a bit if you define a property for your fromURL, as in

@property (nonatomic, retain) NSURL *fromURL;

This way you can use

self.fromURL = [openDlg URL];

and not have to worry about retaining/releasing except in -dealloc where you still need the [fromURL release]

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文