NSURL getting deallocated almost immediately after creation (Objective C)
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 set开发者_运维技巧CanChooseDirectories: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?!?
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]
精彩评论