Aug*_*Aug 2 delegates objective-c nsstream
我是Objective-C的新手.我正在努力学习如何使用NSStream.我刚刚使用Apple支持的简单代码.此代码应该从我的桌面中的文件打开一个流,并在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;
}
Run Code Online (Sandbox Code Playgroud)
运行循环的运行时间不够长,无法调用委托方法.
加:
[[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:2.0]];
Run Code Online (Sandbox Code Playgroud)
打开流后立即.这只在没有GUI的程序中是必需的 - 否则运行循环将为您旋转.
如果你想绝对确定stream:handleEvent:在退出之前已经调用过,那么在该方法中设置一个(全局)标志并将其runUntilDate:置于一个while测试该标志的循环中:
while( !delegateHasBeenNotified ){
[[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.5]];
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2656 次 |
| 最近记录: |