【问题标题】:NSStream reading\writing outside the delegate method handleEvent:eventCodeNSStream在委托方法handleEvent:eventCode之外读\写
【发布时间】:2009-11-29 17:15:01
【问题描述】:

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

我认为我可以在委托方法内进行读\写,但在此之外我需要读\写很多次。

帮助! 谢谢你

【问题讨论】:

    标签: iphone sockets nsstream


    【解决方案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/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;
          }
           }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-27
      • 2023-03-07
      • 1970-01-01
      • 2015-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多