How to use NSFileHandle's writeabilityHandler?

2.8k views Asked by At

Starting from OS X 10.7 and iOS 5.0 NSFileHandle has two new properties: readabilityHandler and writeabilityHandler. I tried to use writeabilityHandler, but no luck. The documentation is weird, it looks like they copy-pasted description of readabilityHandler and replaced word read with write.

According to the documentation assigning the block should eventually call the block. It does not.

- (void)sendResponse:(NSData*)dataToSend
{
    _incomingHandle.writeabilityHandler = 
    ^(NSFileHandle* fileHandle)
    {
        [fileHandle writeData:dataToSend]; // exception is thrown here
        fileHandle.writeabilityHandler = nil;
    };
    // Above block is not called without this line:
    //[_incomingHandle writeData:dataToSend];
}

It is called only if I try to write to the handle synchronously [_incomingHandle writeData:dataToSend] which does not make sense. After it is called it throws an exception: EXC_BAD_INSTRUCTION

*** Terminating app due to uncaught exception 'NSFileHandleOperationException', reason:
'*** -[NSConcreteFileHandle writeData:]: Resource temporarily unavailable'

I have also tried to send the data piece by piece. No luck.

Has anyone successfully used this property?

1

There are 1 answers

6
Catfish_Man On

Hmm, do you have a sample project I could try? I haven't had any issues with it, even when doing silly things like nesting handlers. A test case that shows it not working might help figure out what's wrong.

One issue you could be running into is that the use of dispatch_io inside NSFileHandle will modify the properties of any fd you've passed in. That's arguably a bug in NSFileHandle, but is true for now :/