希望你们能帮助我:)
在主线程中,我创建了一个 NSOperation 并将其添加到队列中。该操作所做的是使用 NSURLConnection 连接到数据服务器,保存收到的数据并解析它。
操作.m
- (void)start
{
NSLog(@"opeartion for <%@> started.", [cmd description]);
[self willChangeValueForKey:@"isExecuting"];
_isExecuting = YES;
[self didChangeValueForKey:@"isExecuting"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:_url];
[request setHTTPMethod:@"POST"];
[request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", m_BOUNDARY] forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:_postData];
_connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (_connection == nil)
[self finish];
}
然后在这个 NSURL 委托方法中,我解析刚刚从服务器接收到的数据。
操作.m
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[self parseItems];
}
在数据中,我可以找到诸如 screenItem、CellItem、TextItem 之类的项目,这些项目在到达时发送到主线程以绘制它们。(如果 itemTable 到达,我创建一个 UITableView,或者如果 itemWeb 到达,我创建一个 UIWebView)
使用它发送项目到主线程:
操作.m
- (void) parseItems
{
while ([_data length] > 0)
{
NSInteger type = [self _readByte];
switch (type)
{
case SCREEN:
{
[self _send: [self _readScreen]];
break;
}
case CELL:
{
[self _send: [self _readCell]];
break;
}
// ... A lot of different items
}
}
}
- (void)_send:(CItem*)_item
{
[[NSNotificationCenter defaultCenter] postNotificationName:@"newItem" object:_item];
}
然后在通知接收器中:
AppDelegate.m
- (void) _newItemArrived:(NSNotification *) notification
{
[self performSelectorOnMainThread:@selector(processItem:) withObject:[notification object] waitUntilDone:NO];
}
我的问题是直到 NSOperation 完成后才绘制 UI。我认为 NSPertion 作为一个不同的线程,不会阻塞主线程,但相信这就是正在发生的事情。
这个问题的一些提示?
非常感谢阅读!