如何在NSStream中使用委托?

问题描述:

我是Objective-C的新手。我正在努力学习如何与NSStream合作。我只是使用Apple支持的简单代码。此代码应从我的桌面中的文件打开一个流,并在委托由iStream调用时显示一条简单消息。在代码的最后,我可以看到状态是正确的,但委托永远不会被调用。我错过了什么?如何在NSStream中使用委托?

#import <Foundation/Foundation.h> 

@interface MyDelegate: NSStream <NSStreamDelegate>{ 
} 

- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode ; 

@end 

@implementation MyDelegate 

- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode { 
    NSLog(@"############# in DELEGATE###############"); 
} 

@end 

int main(int argc, const char * argv[]) 
{ 
    @autoreleasepool { 
     MyDelegate* myDelegate=[[MyDelegate alloc]init]; 
     NSInputStream* iStream= [[NSInputStream alloc] initWithFileAtPath:@"/Users/Augend/Desktop/Test.rtf"]; 

     [iStream setDelegate:myDelegate]; 

     [iStream scheduleInRunLoop:[NSRunLoop currentRunLoop] 
          forMode:NSDefaultRunLoopMode]; 
     [iStream open]; 

     NSLog(@" status:%@",(NSString*) [iStream streamError]); 
    } 
    return 0; 
} 

运行循环运行时间不够长,无法调用委托方法。

地址:

[[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:2.0]]; 

打开流之后。这只在没有GUI的程序中是必需的 - 否则运行循环会为你旋转。

如果你想在退出之前绝对确保stream:handleEvent:被调用,设置该方法的(global)标志,并把runUntilDate:while循环,对于标志测试:

while(!delegateHasBeenNotified){ 
    [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.5]]; 
}