我正在尝试创建一个类似终端的应用程序,可以在应用程序运行时显示日志。
当前的实现使用 NSScrollView -> NSTextView。但是,我注意到 NSTextView 的大小对于我的程序来说不够大,并且我无法经常更新 UI。
假设我们有如下所示的示例代码(其他所有内容与全新的 Xcode 应用程序项目相同)。
该程序继续每 0.1 秒向 UI 打印一些垃圾文本并更新视图。我发现程序每次运行4分钟左右就崩溃了。另外我必须在每个垃圾文本之间添加 0.1 秒的延迟。如果我没有设置任何延迟时间,程序就会立即崩溃。我想找到解决这个问题的方法。
我不确定 NSTextView 是否仍然是我的应用程序的最佳选择。如果没有,任何人都可以为我指出正确的方向,即可以像终端应用程序一样运行的视图或视图集合。
提前致谢。
#import "AppDelegate.h"
@implementation AppDelegate
@synthesize window = _window;
@synthesize queue = _queue;
@synthesize theTextView = _theTextView;
- (void)dealloc
{
[super dealloc];
}
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
// Insert code here to initialize your application 322, 40, 895, 720
NSScrollView *scrollview = [[NSScrollView alloc]
initWithFrame:[[_window contentView] frame]];
NSSize contentSize = [scrollview contentSize];
[scrollview setBorderType:NSNoBorder];
[scrollview setHasVerticalScroller:YES];
[scrollview setHasHorizontalScroller:NO];
[scrollview setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
_theTextView = [[NSTextView alloc] initWithFrame:NSMakeRect(0, 0,
contentSize.width, contentSize.height)];
[_theTextView setMinSize:NSMakeSize(0.0, contentSize.height)];
[_theTextView setMaxSize:NSMakeSize(FLT_MAX, FLT_MAX)];
[_theTextView setVerticallyResizable:YES];
[_theTextView setHorizontallyResizable:NO];
[_theTextView setAutoresizingMask:NSViewWidthSizable];
[[_theTextView textContainer] setContainerSize:NSMakeSize(contentSize.width, FLT_MAX)];
[[_theTextView textContainer] setWidthTracksTextView:YES];
[scrollview setDocumentView:_theTextView];
[_window setContentView:scrollview];
[_window makeKeyAndOrderFront:nil];
[_window makeFirstResponder:_theTextView];
[[_theTextView enclosingScrollView] setHasHorizontalScroller:YES];
[_theTextView setHorizontallyResizable:YES];
[_theTextView setAutoresizingMask:(NSViewWidthSizable | NSViewHeightSizable)];
[[_theTextView textContainer] setContainerSize:NSMakeSize(FLT_MAX, FLT_MAX)];
[[_theTextView textContainer] setWidthTracksTextView:NO];
_queue = dispatch_queue_create("com.example.MyQueue", NULL);
[self start];
}
- (void) start {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
[self feed];
});
}
- (void) feed {
while (1) {
dispatch_async(_queue, ^(void){
NSString * displaytext = (NSString *) CFSTR("Testing Line - asdfasdfklqjwer;opfjiasdlk;fjasd\n");
NSAttributedString *string = [[NSAttributedString alloc] initWithString:displaytext];
NSLog(@"Output is %@", string);
// [[_theTextView textStorage] appendAttributedString:string];
[[_theTextView textStorage] beginEditing];
[[_theTextView textStorage] appendAttributedString:string];
[[_theTextView textStorage] endEditing];
[_theTextView scrollRangeToVisible:NSMakeRange([[_theTextView string] length], 0)];
[string release];
});
usleep(100000);
}
}
@end