希望你们能帮助我:)NSOperation在解析数据时绘制用户界面?
在主线程中,我创建一个NSOperation并将其添加到队列中。 该操作所做的是使用NSURLConnection连接到数据服务器,保存receivedData并解析它。
Operation.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委托方法我分析我刚刚从服务器接收到的数据。
Operation.m
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[self parseItems];
}
在数据上,我可以找到喜欢的物品,例如,screenItem,CellItem,TextItem我发送给主线程绘制他们同时到达。 (我创建一个UITableView如果itemTable到达,或创建一个UIWebView如果itemWeb到达)
使用该发送项目主线:
Operation.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。我认为NSOpertion,作为一个不同的线程,不会阻止主线程,但相信这是发生了什么。
这个问题的一些提示?
非常感谢您的阅读!
我刚刚回答了一个相关问题:http://stackoverflow.com/questions/11158294/nsoperation-mainqueue-issue/13477136#13477136。希望这可以帮助。 – 2012-11-20 16:21:09