1

希望你们能帮助我:)

在主线程中,我创建了一个 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 作为一个不同的线程,不会阻塞主线程,但相信这就是正在发生的事情。

这个问题的一些提示?

非常感谢阅读!

4

2 回答 2

0

So I know this is a pretty old question but I ran into the same issue and after hours of going through documentation and blogs I found a great solution in this post from Wim Haanstra http://www.depl0y.com/?p=345

Putting your NSOperation in an infinite loop until you get data back should do the trick!

于 2011-10-19T16:38:36.577 回答
0

你在用NSOperationQueue吗?

查看这个问题的答案NSOperation blocks UI painting? 有关如何使用在另一个线程上异步运行的 NSOperation 的通知来更新 UI 的简单示例。

更新

  1. NSURLConnection 通过委托本身支持异步连接。你应该使用这个。如果您有特定问题,您应该描述这些问题。
  2. 查看ASIHTTPRequest库。
  3. 如果你真的想使用这种方法,你可以尝试同步运行 NSURLConnection (使用类方法sendSynchronousRequest:returningResponse:error:)。由于连接在后台线程上,您的应用程序将保持响应。但是,在收到所有数据之前,您将无法更新任何内容。
于 2010-01-22T11:18:00.997 回答