NSStream reading\writing outside the delegate method handleEvent:eventCode
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 writeToS开发者_如何学运维tream: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
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
-(void)myFunction1 {
[self writeToStream:somedata];
}
-(void)myFunction2 {
readData=[self readFromStream];
}
- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode {
switch(eventCode) {
case NSStreamEventHasBytesAvailable: {
[self myFunction2];
break;
}
}
}
精彩评论