Re: non-blocking file writes
Re: non-blocking file writes
- Subject: Re: non-blocking file writes
- From: Dustin Voss <email@hidden>
- Date: Thu, 10 Jul 2003 09:52:56 -0700
On Monday, July 7, 2003, at 07:40 AM, Devon E Bowen wrote:
I'm a UNIX guy but with little Cocoa experience. I'm looking for a way
to read and write data (ints, chars, etc) to a file. Sounds simple
enough but I want to do it in a way that guarantees non-blocking I/O.
I poked around through the docs and ran across NSFileHandle which seems
to support methods for non-blocking reads (readInBackgroundAndNotify)
but not for writes.
So the question is... is there a better way to do this? Maybe another
class I should be looking at? It seems like this is a pretty basic
thing to want to do, no? Or do Cocoa programmers usually assume that
writes will always work quickly enough to not worry about it? That
would
seem like bad coding style to me. Personally, I would prefer never to
see that little beach ball spinning in my code.
Any help or tips are appreciated...
The best way to handle this is with the Core Foundation classes
CFReadStream and CFWriteStream. These are documented at
<
http://developer.apple.com/documentation/CoreFoundation/Conceptual/
CFStreams/index.html> and "CFStream.h". They can perform tasks in the
background and put a call-back on the run loop when finished. Here's
what you'll need to do for CFReadStream; CFWriteStream has parallel
functions:
1. Create the stream using CFReadStreamCreateWithFile().
2. Set up your callbacks with CFReadStreamSetClient().
3. Add it to the run-loop with CFReadStreamScheduleWithRunLoop().
4. Open the stream with CFReadStreamOpen().
5. You'll get a call-back when they are open. Do whatever you need to.
6. You'll get further call-backs when information is available to be
read, when writing is possible, when you reach EOF, or when you get an
error. You can also poll for this information.
7. When you are done with the streams, call
CFReadStreamUnscheduleFromRunLoop(), CFReadStreamClose(), and
CFRelease().
Don't worry about CFStreamClientContext. That's useful for strict C
programs. You can get away with leaving all fields NULL, or using the
info field for user data.
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.