NSURL 在创建后几乎立即被释放(目标 C)
在我的代码中,我在应用程序委托的头文件中创建了一个名为 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
听起来你需要阅读 内存管理编程指南。
这里发生的事情是,您的
fromURL
变量是一个 ivar(至少,我假设它是一个 ivar,您可能已将其设为全局变量)。您在方法中分配给它。但是您没有处理内存管理,因此当控制权返回到运行循环并且自动释放池耗尽时,您的fromURL
ivar 最终会指向已释放的对象。您需要根据需要保留和释放。对于这个特定的方法,我可能会使用并且也不要忘记在您的
-dealloc
方法中释放fromURL
。如果您为
fromURL
定义一个属性,则可以简化一点,就像这样,您可以使用这种方式
,而不必担心保留/释放,除了在
-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, yourfromURL
ivar ends up pointing at a released object. You need to retain and release as appropriate. For this particular method I might useAnd 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 inThis way you can use
and not have to worry about retaining/releasing except in
-dealloc
where you still need the[fromURL release]