NSStream在委托方法handleEvent:eventCode之外读取\写入

时间:2009-11-29 17:15:02

标签: iphone sockets nsstream

在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;
      }
       }
}

我想我可以在委托方法中读取\ write,但我需要在外面多次读取\ write。

帮助! 谢谢你

1 个答案:

答案 0 :(得分:-1)

stream类可能在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/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;
      }
       }
}