[英]How to use delegate in NSStream?
I am a newbie in Objective-C. 我是Objective-C的新手。 I am trying to learn how to work with
NSStream
. 我正在尝试学习如何使用
NSStream
。 I just used simple code from Apple Support. 我只是使用Apple支持提供的简单代码。 This code should open a stream from a file in my Desktop and show a simple message when the delegate is called by iStream.
此代码应从我的桌面文件中打开流,并在iStream调用委托时显示一条简单消息。 At the end of the code, I can see the status is correct, but the delegate never gets called.
在代码末尾,我可以看到状态正确,但是从未调用过该委托。 What am I missing?
我想念什么?
#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;
}
The run loop isn't running long enough for the delegate method to be called. 运行循环的运行时间不足以调用委托方法。
Add: 加:
[[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:2.0]];
right after you open the stream. 在打开流后。 This is only necessary in a program without a GUI -- otherwise the run loop would be spun for you.
这仅在没有GUI的程序中是必需的-否则将为您旋转run循环。
If you want to be absolutely sure that stream:handleEvent:
has been called before exiting, set a (global) flag in that method and put the runUntilDate:
in a while
loop that tests for the flag: 如果要绝对确定在退出前已调用
stream:handleEvent:
,请在该方法中设置一个(全局)标志,并将runUntilDate:
放入测试该标志的while
循环中:
while( !delegateHasBeenNotified ){
[[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.5]];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.