iOS 程式在UITextView中顯示NSLog日誌的方法,

來源:互聯網
上載者:User

標籤:

 最近開發程式,需要做個給測試人員的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日誌的方法,

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.