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

首先在控制器中声明日志显示的 logTextView

@property (nonatomic, strong)UITextView *logTextView;

然后在代码中实现以下两个方法:

- (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];

即可。

你可能感兴趣的:(Tips:iOS程序在UITextView中显示NSLog日志的方法)