Re: Running an NSTask Within an NSThread
Re: Running an NSTask Within an NSThread
- Subject: Re: Running an NSTask Within an NSThread
- From: Jonathan Dann <email@hidden>
- Date: Sun, 27 Jan 2008 22:06:55 +0000
Thanks James,
You were half-right with the over-releasing thing. All my code for
running the task is in a TaskController object, which was being
autoreleased after the task was run, but before the NSTaskDidTerminate
was sent. I'd registered the object as an observer for this
notification but not removed is as the observer in the dealloc method
for the class! It suddenly occurred to me that a notification was
being sent to a dealloc'd object.
Now I have the problem of my taskController being dealloc'd before the
task has finished (whether its in a new thread or not) so the
NSTaskDidTerminateNotification is not being received by the object. I
currently have a class method that instantiates my TaskController
object, this is called from my NSDocument subclass. So NSDocument
subclass calls:
// NSDocument subclass implementation
- (IBAction)runTask:(id)sender;
{
TaskController *tC = [[TaskController
defaultControllerForDocument:self];
[tC performTask];
}
// TaskController.m
+ (TaskController *)defaultController;
{
TaskController *controller = [[self alloc] init];
return [controller autorelease];
}
- (id)init;
{
if (![super init])
return nil;
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(taskDidTerminate:)
name:NSTaskDidTerminateNotification object:nil];
return self;
}
- (void)dealloc;
{
[[NSNotificationCenter defaultCenter] removeObserver:self]; // here's
the fix for the crash
[super dealloc];
}
- (void)performTask;
{
task = [[NSTask alloc] init];
//configure task
[task launch];
}
- (void)taskDidTerminate:(NSNotification *)notification;
{
[task release];
task = nil;
// do important stuff
}
This currently adheres to the memory management conventions, and
removing the autorelease from the -+defaultControllerForDocument:
method and moving it to the -taskDidTerminate: method would solve my
problem, but it feels hacky as it goes against the convention (or does
it?!). What I need it a more elegant solution. I also need to
account for the times when the task does not finish and just waits for
user input.
I'm not so sure about using -waitUntilExit as that polls, but thanks
for the advice. Any ideas now I've solved the crash?
Thanks,
Jon
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden