views:

441

answers:

1

Hi, 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

A: 

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%5FClass/Reference/Reference.html#//apple%5Fref/occ/instm/NSObject/performSelectorOnMainThread%3AwithObject%3AwaitUntilDone:

And general overview of Cocoa programming: http://developer.apple.com/iphone/library/documentation/Cocoa/Conceptual/CocoaFundamentals/CoreAppArchitecture/CoreAppArchitecture.html#//apple%5Fref/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;
      }
       }
}
Eld