Trouble Writing to File With NSFileHandle
Trouble Writing to File With NSFileHandle
- Subject: Trouble Writing to File With NSFileHandle
- From: Matthew Miller <email@hidden>
- Date: Sun, 03 Dec 2006 12:31:22 -0500
I am trying to log some events in a file during the execution of an
application. The events are generated in response to NSNotifications
sent to the defaultCenter. The app is set up as a multi-document
Cocoa app. The NSFileHandle is allocated in the init() method of
MyDocument.m as such:
// instance variable defined as NSString *
statusLogName = [[NSString alloc]
initWithString:@"[full path]/status.log"];
// check if the file exists
if(![[NSFileManager defaultManager]
fileExistsAtPath:statusLogName]) {
[[NSFileManager defaultManager] createFileAtPath:statusLogName
contents:nil
attributes:nil];
}
fhlocal = [NSFileHandle
fileHandleForWritingAtPath:statusLogName];
NSLog(@"Descriptor for status = %d", [fhlocal fileDescriptor]);
fhStatus = [[NSFileHandle alloc]
initWithFileDescriptor:[fhlocal fileDescriptor]];
The call to NSLog returns a valid descriptor number (e.g. 6). In a
observer method, I use the following code:
- (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.
Now I'm starting to believe this has something to do with the fact
that it's in response to a notification. I've written a test
Foundation app that runs all in the main() function using the same
logic (create file if it doesn't work, get the descriptor, allocate
NSFileHandle, write, release) and it works. This is not even
central to the application itself, I just need some ability to log
what's happening.
Please help, I just can't seem to solve this.
Thanks,
Matt
_______________________________________________
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