首先在控制器中聲明日志顯示的 logTextView
@property (nonatomic, strong)UITextView *logTextView;
然后在代碼中實(shí)現(xiàn)以下兩個方法:
- (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];
}
最后調(diào)用
[self redirectSTD:STDOUT_FILENO];
[self redirectSTD:STDERR_FILENO];
即可浅妆。