Search code examples
objective-cmacoscocoansfilehandle

How to check for End-of-File using NSFileHandle's readabilityHandler?


I am reading data from a NSFileHandle (from a NSPipe) using a readabilityHandler block:

fileHandle.readabilityHandler = ^( NSFileHandle *handle ) {
     [self processData: [handle availableData]];
}

This works fine, I get all the data I expect fed to my processData method. The problem is that I need to know when the last chunk of data was read. availableData should return an empty NSData instance if it reached end-of-file, but the problem is that the reachability handler is not called again on EOF.

I can’t find anything about how to get some kind of notification or callback on EOF. So what am I missing? Is Apple really providing an asynchronous reading API without an EOF callback?

By the way, I cannot use the runloop based readInBackgroundAndNotify method since I don’t have a runloop available. If I cannot get this to work with the NSFileHandle API I probably will directly use a dispatch source to do the IO.


Solution

  • I'm afraid you're out of luck doing this with NSFileHandle if you can't use readInBackgroundAndNotify.

    Two solutions I see:

    1. Create a runloop and then use readInBackgroundAndNotify.
    2. Roll your own implementation using dispatch_io_*