Re: Trouble Writing to File With NSFileHandle
Re: Trouble Writing to File With NSFileHandle
- Subject: Re: Trouble Writing to File With NSFileHandle
- From: "stephen joseph butler" <email@hidden>
- Date: Sun, 3 Dec 2006 12:46:46 -0600
2006/12/3, Matthew Miller <email@hidden>:
fhlocal = [NSFileHandle
fileHandleForWritingAtPath:statusLogName];
NSLog(@"Descriptor for status = %d", [fhlocal fileDescriptor]);
fhStatus = [[NSFileHandle alloc]
initWithFileDescriptor:[fhlocal fileDescriptor]];
Why do you do this? It would be much simpler to just say fhStatus =
[fhlocal retain]; It would also solve your problems...
- (void)statusPosted:(NSNotification *)notification
{
NSString *msg = [notification object];
NSLog(@"Before write status %d...", [fhStatus fileDescriptor]);
[fhStatus writeData:[msg dataUsingEncoding:NSASCIIStringEncoding]];
NSLog(@"After write status...");
}
The NSLog gives me the same descriptor (e.g. 6) but I get the
following output to stdout:
2006-12-03 11:50:20.161 Craps[6796] Before write status 6...
2006-12-03 11:50:20.162 Craps[6796] Exception raised during posting
of notification. Ignored. exception: *** -[NSConcreteFileHandle
writeData:]: Bad file descriptor
At first I thought it was because the call to [NSFileHandle
fileHandleForWritingAtPath:] method call was returning a variable
that was not persistent. So I changed to alloc a full instance using
the fileDescriptor. But that didn't fix the problem.
You're close here, but you missed how to fix it.
fileHandleForWritingAtPath: creates an autoreleased object which will
both (a) deallocate and (b) close its file descriptor on the next pass
through the run loop. That you've stored the descriptor elsewhere
doesn't matter a bit. Your exception happens because the descriptor
has been closed.
The reason it works in your simple tool is because you probably aren't
running the run loop, or the autoreleased object ends up in a pool
that isn't released until the very end.
Perhaps you need to spend some more time understanding Cocoa memory
allocation paradigm.
http://developer.apple.com/documentation/Cocoa/Conceptual/MemoryMgmt/index.html
_______________________________________________
Cocoa-dev mailing list (email@hidden)
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