Subclassing NSInputStream

Subclassing NSInputStream is a problem that has been plaguing Cocoa developers for a long time. Googling “subclass nsinputstream” reveals that people have been having issues with this for six or seven years. While the documentation seems to indicate that it should be fairly straightforward, actually trying to do so reveals several hairy spots.

For example, if you try to use a custom NSInputStream as the body of an NSURLRequest, you’ll get an exception that your input stream doesn’t respond to _scheduleInCFRunLoop:forMode:. So then you create an empty stub for that method. You’re good, right? Nope! Now you fail with an unimplemented _setCFClientFlags:callback:context:. So you implement that, and you’re good, right? Nope! You fail now with an unimplemented _unscheduleFromCFRunLoop:forMode:. So you put that in as a stub, and you’re good? Well, you don’t get any more exceptions… but nothing ever gets read from your stream. Minor details…

Well, the dark night of ignorance and inability is over!

BJ Homer has just posted an article on how he got his NSInputStream subclass to work. He’s even posted a demo on his GitHub account. I won’t spoil any of the details here; go read it for yourself! His solution is really quite clever.

(And as a side note, at the time of this writing, there are 2,272 occurrences of the letter ‘n’ on his blog’s home page.)