I created a NSInputStream to load content from a file(IOS):
NSString* fileName = [[NSBundle mainBundle] pathForResource:@"resource" ofType:@".dat"];
NSInputStream* dataStream = [NSInputStream inputStreamWithFileAtPath:fileName];
if (dataStream == nil) {
NSLog(@"load asset failed");
return;
}
[dataStream setDelegate:self];
[dataStream scheduleInRunLoop:[NSRunLoop currentRunLoop]
forMode:NSDefa开发者_StackOverflowultRunLoopMode];
[dataStream open];
Then, add event handler:
- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode {
switch(eventCode) {
case NSStreamEventEndEncountered: {
[stream removeFromRunLoop:[NSRunLoop currentRunLoop]
forMode:NSDefaultRunLoopMode];
break;
}
}
}
I want to catch the event:NSStreamEventEndEncountered, but not happend. I can only catch NSStreamEventOpenCompleted and NSStreamEventHasBytesAvailable.
Anything wrong? Thanks for any help!
I can't see anything wrong with the code you've posted. Make sure that when you're finished with the stream that you are closing it yourself rather than simply relying on getting an NSStreamEventEndEncountered
notification, which you can do simply with something like this:
- (void) disconnect {
// Close all open streams
[inputStream close];
[outputStream close];
}
You'll usually only get NSStreamEventEndEncountered
if the connection is closed by the other end of the stream, which depending on what you're doing may be beyond your control.
I just ran in to this. Replace NSStreamEventEndEncountered with 4 in the switch/case statement.
NSStreamEventEndEncountered as an NSStream enum doesn't end up being caught in a case statement.
None of these answers are correct. To trigger the NSStreamEventEndEncountered event, you must attempt to read data from the input stream when there is no data to read (in other words, when the paired output stream stops writing data).
精彩评论