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

即可。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,095评论 19 139
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 176,272评论 25 709
  • 我喜欢现在的我 懵懂已经褪去 风霜未曾侵袭 心中有爱 不忧 亦不惧 愿你也喜欢现在的你自己
    贾贾装装阅读 1,387评论 0 1
  • 六月的燥风 瞌睡着梦想 身躯变得沉重 总想在阴凉中躺下 心无奈着这惰情的思绪 灵魂跋涉过无人的雪山 以满心的热力 ...
    淘猴侯孙行阅读 2,695评论 12 10
  • 参考自:android 软键盘在全屏下的布局计算问题在你的工程添加AndroidBug5497Workaround...
    空中飞客阅读 1,684评论 0 0

友情链接更多精彩内容