NSStream 在委托方法handleEvent:eventCode 之外读取\写入
在iPhone应用程序中,我通过wifi有一个套接字连接,我需要从inputStream读取并写入outputStream。问题是流管理是事件驱动的,我必须等待事件 NSStreamEventHasBytesAvailable 才能读取。所以我不知道何时在handleEvent:eventCode委托方法之外读取\写入。
我尝试了 while 循环,但我意识到在 while 循环期间应用程序不会接收委托消息并且永远不会停止:
伪代码:
-(void) myFunction {
canRead=NO;
[self writeToStream:someData];
while(!canRead) { };
readData=[self readFromStream];
}
- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode {
switch(eventCode) {
case NSStreamEventHasBytesAvailable: {
canRead=YES;
break;
}
}
}
我认为我可以在委托方法内读\写,但我需要读\写很多以外的时间。
帮助! 谢谢
in an iPhone app, I have a socket connection through wifi, and I need to read from inputStream and write to outputStream. The problem is that stream management is event-driven, and I have to wait for event NSStreamEventHasBytesAvailable before reading. So I can't know when reading\writing outside the handleEvent:eventCode delegate method.
I tried a while loop, but I realized that during the while loop the app doesn't receive delegate messages and never stops:
Pseudo-code:
-(void) myFunction {
canRead=NO;
[self writeToStream:someData];
while(!canRead) { };
readData=[self readFromStream];
}
- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode {
switch(eventCode) {
case NSStreamEventHasBytesAvailable: {
canRead=YES;
break;
}
}
}
I think I could read\write inside the delegate method, but I need to read\write many times outside that.
Help!
Thankyou
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
流类可能在 EventQueue 上放置了一个事件来调用“stream:handleEvent:”。如果您的代码不会将控制权返回给事件处理程序,则无法读取事件队列。您可能想要做的而不是这种方式是:
请参阅 http://developer.apple.com/iphone/library/documentation/cocoa/Reference/Foundation/Classes/NSObject_Class/Reference /Reference.html#//apple_ref/occ/instm/NSObject/performSelectorOnMainThread:withObject:waitUntilDone:
Cocoa 编程的一般概述:http://developer.apple.com/iphone/library/文档/Cocoa/Conceptual/CocoaFundamentals/CoreAppArchitecture/CoreAppArchitecture.html#//apple_ref/doc/uid/TP40002974-CH8-SW45
The stream class probably placed an event on the EventQueue to call "stream:handleEvent:". The event queue can't be read if your code won't return control to the event handler. What you probably want to do instead of that way is:
See http://developer.apple.com/iphone/library/documentation/cocoa/Reference/Foundation/Classes/NSObject_Class/Reference/Reference.html#//apple_ref/occ/instm/NSObject/performSelectorOnMainThread:withObject:waitUntilDone:
And general overview of Cocoa programming: http://developer.apple.com/iphone/library/documentation/Cocoa/Conceptual/CocoaFundamentals/CoreAppArchitecture/CoreAppArchitecture.html#//apple_ref/doc/uid/TP40002974-CH8-SW45