背景
我的应用程序从网络流中获取数据,并更改屏幕上 UI 元素的值。其中一个元素是 UITextView,它作为传入数据的一种日志。每当应用程序接收到带有传入数据本质的 "HasBytesAvailable" NSStreamEvent 时,它都应该更新。例如,如果传入的数据与蛋糕有关,则文本视图将更新为类似于 "6/22/12 8:00 - 收到了蛋糕" 的内容。下面展示了它更新的示例。
[logString insertString:@"This is an update\n" atIndex:0];
//logstring is a MutableString I use to hold my UITextView's text
[logString insertString:timeString atIndex:0]; //timestring is current time
logView.text = logString; //logView is my UITextView
[logView flashScrollIndicators];
//logstring and logview declaration and implementation
@property (nonatomic,retain) IBOutlet UITextView *logView;
@property (nonatomic,retain) NSMutableString *logString;
logString = [[NSMutableString alloc] initWithString:@"-logging started\n"];
问题
只要我不尝试滚动TextView,更新工作就像我想要的那样。然而,如果我滚动文本并按住它,可能足够长时间调用我的更新代码,当我停止滚动时,应用程序会崩溃。我可以轻松地 flick through the text,只有在处理传入数据并且我仍在滚动时才会崩溃。此外,在我滚动时,没有其他内容会更新。所有应该由接收到的数据更新的标签都保持不变。
我的想法好像这个应用程序不能同时处理滚动和处理传入数据。我不确定这是因为我在内存管理方面做错了什么,还是需要覆盖一些滚动功能,或者完全是其他原因。任何帮助或想法都将不胜感激。
解决方案如trumpetlicks所说,我需要为我的网络任务实现多线程处理。为此,我执行了以下操作:
初始化时:
NSOperationQueue *networkQueue = [NSOperationQueue new];
NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(initNetworkCommunication) object:nil];
[networkQueue addOperation:operation];
[operation release];
在initNetworkCommunication函数中,在初始化CFSocketpair和流之后:
[[NSRunLoop currentRunLoop] run]; //necessary to handle stream events