我正在尝试学习如何使用单元测试在iPhone上使用NSInputStream类。我可以使用轮询方法让NSStream从文件中读取数据,但由于某种原因,委托/事件方法无效。
我在下面发布了相关代码。请忽略内存泄漏错误,因为我只是想确保我知道如何在沙盒环境中使用NSStream类,然后再将其放入我的大型项目中。
我想知道我是否遗漏了关于运行循环如何工作的内容?
这是一个逻辑测试,它创建一个从文件中读取的流媒体类。
#import "StreamingTests.h"
#import "Streamer.h"
@implementation StreamingTests
- (void) testStream {
NSLog(@"Starting stream test.");
Streamer * streamer = [[Streamer alloc] init];
streamer.usePolling = NO;
streamer.readingStream = YES;
NSThread * readThread = [[NSThread alloc] initWithTarget:streamer selector:@selector(startStreamRead:) object:nil];
[readThread start];
while(streamer.readingStream) {
[NSThread sleepForTimeInterval:0.5];
}
[readThread cancel];
}
@end
这是一个从NSStream读取的简单测试助手对象。当usePolling == YES时,它会读取数据并输出相应的NSLog消息。但是,如果usePolling == NO,则永远不会调用委托流事件函数。
@implementation Streamer
@synthesize readingStream, usePolling;
- (void) startStreamRead:(NSObject*) context {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSLog(@"starting stream read.");
readingStream = YES;
/*
NSURL * url = [NSURL URLWithString:@"http://www.google.com"];
NSLog(@"Loading: %@",[url description]);
NSInputStream * inStream = [[NSInputStream alloc] initWithURL:url];
*/
NSInputStream * inStream = [[NSInputStream alloc] initWithFileAtPath:@"sample.ttc"];
if(!usePolling) {
[inStream setDelegate: self];
[inStream scheduleInRunLoop: [NSRunLoop currentRunLoop]
forMode: NSDefaultRunLoopMode];
}
[inStream open];
if(usePolling) {
while(1) {
if([inStream hasBytesAvailable]) {
uint8_t buf[1024];
unsigned int len = 0;
len = [(NSInputStream *)inStream read:buf maxLength:1024];
NSLog(@"Read: %d",len);
}
NSStreamStatus status = [inStream streamStatus];
if(status != NSStreamStatusOpen && status != NSStreamStatusOpening) {
NSLog(@"Stream not open.");
break;
}
}
readingStream = NO;
NSStreamStatus status = [inStream streamStatus];
NSError * error = [inStream streamError];
NSLog(@"Status: %d Error Desc: %@ Reason: %@",(int)status,[error localizedDescription], [error localizedFailureReason]);
[pool release];
}
}
- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode {
NSMutableData * _data = nil;
NSNumber * bytesRead = nil;
NSLog(@"Event fired.");
switch(eventCode) {
case NSStreamEventHasBytesAvailable:
{
if(!_data) {
_data = [[NSMutableData data] retain];
}
uint8_t buf[1024];
unsigned int len = 0;
len = [(NSInputStream *)stream read:buf maxLength:1024];
if(len) {
[_data appendBytes:(const void *)buf length:len];
// bytesRead is an instance variable of type NSNumber.
//[bytesRead setIntValue:[bytesRead intValue]+len];
NSLog(@"Read %d bytes",len);
} else {
NSLog(@"no buffer!");
}
break;
}
case NSStreamEventEndEncountered:
{
[stream close];
[stream removeFromRunLoop:[NSRunLoop currentRunLoop]
forMode:NSDefaultRunLoopMode];
[stream release];
stream = nil; // stream is ivar, so reinit it
readingStream = NO;
break;
}
default:
{
NSLog(@"Another event occurred.");
break;
}
// continued ...
}
}
@end
提前致谢,
B'/ P>
答案 0 :(得分:0)
原因应该是运行循环被阻止,因为单元测试正在执行。您可以参考the NSRunLoop documentation方法
runUntilDate:
可能会帮助您在执行单元测试的线程中运行主运行循环,如下所示:
[[NSRunLoop mainRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:1]];
这使运行循环运行1秒,从而有时间处理文件的一部分。应该注意的是,这不提供单元测试的可靠方式(因为时间间隔可能根据运行循环大小而不同),因此可能不合适。通过为您的单元提供一个接口,可用于检查输入流读取操作的状态(具有读取完成状态),例如
-(BOOL)hasFinishedReadingFile
单元测试可以重复执行运行循环,直到上面的方法返回TRUE并且文件被完全读取。
添加: This question on stackoverflow也以不同的方式解决问题。