码迷,mamicode.com
首页 > 移动开发 > 详细

iOS 程序在UITextView中显示NSLog日志的方法,

时间:2015-12-07 20:49:52      阅读:237      评论:0      收藏:0      [点我收藏+]

标签:

 最近开发程序,需要做个给测试人员的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];

就可以实现输出打印,

 

  

 

iOS 程序在UITextView中显示NSLog日志的方法,

标签:

原文地址:http://www.cnblogs.com/ZhenShi/p/5027286.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!