我缺少什么? : iPhone Objective-C NSInputStream initWithData
我正在从 NSData 对象创建 NSInputStream,但创建流后报告 hasBytesAvailable 没有:
NSData* data = [outputStream propertyForKey: NSStreamDataWrittenToMemoryStreamKey];
NSLog(@"creating stream with data 0x%x length %d", [data bytes], [data length]);
NSInputStream *insrm = [[NSInputStream alloc] initWithData:data];
[insrm open];
uint8_t* buf = NULL;
NSUInteger len;
BOOL result = [insrm getBuffer:&buf length:&len];
BOOL hasbytes = [insrm hasBytesAvailable];
NSLog(@"getBuffer:%d hasBytes:%d", result, hasbytes);
NSLog(@"created inputstream data %d len %d", buf, len);
日志:
[26797:20b] creating stream with data 0x7050000 length 34672
[26797:20b] getBuffer:0 hasBytes:0
[26797:20b] created inputstream data 0 len 0
我在这里缺少什么?
I'm creating an NSInputStream from an NSData object but once created the stream reports NO for hasBytesAvailable:
NSData* data = [outputStream propertyForKey: NSStreamDataWrittenToMemoryStreamKey];
NSLog(@"creating stream with data 0x%x length %d", [data bytes], [data length]);
NSInputStream *insrm = [[NSInputStream alloc] initWithData:data];
[insrm open];
uint8_t* buf = NULL;
NSUInteger len;
BOOL result = [insrm getBuffer:&buf length:&len];
BOOL hasbytes = [insrm hasBytesAvailable];
NSLog(@"getBuffer:%d hasBytes:%d", result, hasbytes);
NSLog(@"created inputstream data %d len %d", buf, len);
Log:
[26797:20b] creating stream with data 0x7050000 length 34672
[26797:20b] getBuffer:0 hasBytes:0
[26797:20b] created inputstream data 0 len 0
What am I missing here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
此代码将用于读取您的流:
如果您不打开流,
getBuffer:length:
将返回 YES。但是,它最初在 buf 或 len 中不会有有效值。我认为这是因为它是非阻塞操作。大概值将在稍后填写。无论如何,如果你想阻止,请使用我上面的方法。如果您不想阻塞,则应该在运行循环上安排输入流并实现委托方法
stream:handleEvent:
。然而,即使这样也不能保证你永远不会阻塞。相反,您可能想要寻找一个提供另一层抽象并为您在单独线程上处理流的库。This code will work for reading your stream:
getBuffer:length:
will return YES if you do not open the stream. However, it will not initially have valid values in buf or len. I think this is due to the fact that it is a non-blocking operation. Presumably values will be filled in later.In any case, if you want to block, use what I have above. If you do not want to block, you should schedule the input stream on the run loop and implement the delegate method
stream:handleEvent:
. However, even this does not guarantee that you will never block. Instead you might want to look for a library that offers another layer of abstraction and handles the stream on a separate thread for you.