最近开发程序,需要做个给测试人员的demo,客户端可以实时 显示程序的打印日志的功能,
查找了很多的资料找到个方法,利用NSPipe即可以实现,
苹果官方解释:
objects provide an object-oriented interface for accessing pipes. An NSPipe
object represents both ends of a pipe and enables communication through the pipe. A pipe is a one-way communications channel between related processes; one process writes data, while the other process reads that data. The data that passes through the pipe is buffered; the size of the buffer is determined by the underlying operating system.NSPipe
is an abstract class, the public interface of a class cluster.
NSPipe是一个抽象类,一类集群的公共接口。通过NSPipe 我们可以方便的读取和写入进程数据,
如果想实现将 程序的实时日志打印,可以在控制器中添加下边方法
- (void)redirectNotificationHandle:(NSNotification *)nf{ // 通知方法
NSData *data = [[nf userInfo] objectForKey:NSFileHandleNotificationDataItem];
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
self.logTextView.text = [NSString stringWithFormat:@"%@\n\n%@",self.logTextView.text, str];// logTextView 就是要将日志输出的视图(UITextView)
NSRange range;
range.location = [self.logTextView.text length] - 1;
range.length = 0;
[self.logTextView scrollRangeToVisible:range];
[[nf object] readInBackgroundAndNotify];
}
- (void)redirectSTD:(int )fd{
NSPipe * pipe = [NSPipe pipe] ;// 初始化一个NSPipe 对象
NSFileHandle *pipeReadHandle = [pipe fileHandleForReading] ;
dup2([[pipe fileHandleForWriting] fileDescriptor], fd) ;
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(redirectNotificationHandle:)
name:NSFileHandleReadCompletionNotification
object:pipeReadHandle]; // 注册通知
[pipeReadHandle readInBackgroundAndNotify];
}
执行
[self redirectSTD:STDOUT_FILENO];
[self redirectSTD:STDERR_FILENO];
就可以实现输出打印,