我是Objective-C的新手。我正在尝试学习如何使用NSStream。我只是使用了来自Apple Support的简单代码。这段代码应该会从我的桌面中的文件中打开一个流,并在iStream调用委托时显示一条简单的消息。在代码的最后,我可以看到状态是正确的,但是委托永远不会被调用。我遗漏了什么?
#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;
}发布于 2012-09-03 03:03:25
run循环运行的时间不够长,无法调用委托方法。
添加:
[[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:2.0]];就在你打开小溪之后。这只在没有GUI的程序中是必需的--否则run循环将为您旋转。
如果您希望绝对确保在退出之前已调用了stream:handleEvent:,请在该方法中设置一个(全局)标志,并将runUntilDate:放入用于测试该标志的while循环中:
while( !delegateHasBeenNotified ){
[[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.5]];
}https://stackoverflow.com/questions/12238828
复制相似问题