Error deserializing json stream

2019-06-02 08:10发布

问题:

I have an NSInputStream *inputStream receiving small JSON objects from a network connection. If I read the stream to a buffer like so:

NSError *err = nil;
uint8_t buffer[1024];
NSMutableData *data = [[NSMutableData alloc] init];
while ([inputStream hasBytesAvailable]) {
    int const len = [inputStream read:buffer maxLength:sizeof(buffer)];
    if (0 < len) {
        [data appendBytes:buffer length:len];
    }
}
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&err];

then I get the JSON I expect; but this is very brittle, as it assumes that there is exactly one JSON object to read. With this scheme, I could end up trying to deserialize {"cheese":17}{"ch, which is obviously invalid. I'd rather use

NSError *err = nil;
NSDictionary *json = [NSJSONSerialization JSONObjectWithStream:inputStream options:0 error:&err];

but, but stepping through with the debugger, I discovered that this last line does not return, and logs no error! What's the right approach?