1

我有一个 iphone 应用程序,在加载视图控制器时,我想在后台线程上调用 Web 服务、获取和解析 XML。然后在线程完成后更新ui,然后触发另一个线程在另一个后台线程中执行第二次操作。

有点像链接线程调用:

  1. UI 线程 -> 创建 BG 线程
  2. BG 线程 -> 调用 XML 服务并获取结果
  3. UI Thread -> 更新 BG Thread 操作成功的 UI
  4. BG Thread -> 触发操作的第 2 部分

全部加载应用程序。

问题是我的第一个 BG 线程操作似乎永远不会结束。我waitUntilAllOperationsAreFinished在第 2 步完成后添加了一个电话,只是为了看看发生了什么,我的应用程序似乎永远不会超过那个点。

这是一种基本的骨架实现:

- (void) viewDidLoad 
{
    queue = [[NSOperationQueue alloc] init];
[queue setMaxConcurrentOperationCount:1];

    //other stuff

    [self loadFriendsInBackgroundThread];
}

- (void) loadFriendsInBackgroundThread
{   
    NSInvocationOperation *operation = [NSInvocationOperation alloc];
    operation = [operation initWithTarget:self selector:@selector(invokeLoadingOfFriends:) object: nil];

    [queue addOperation:operation];
[operation release];
}

- (void) invokeLoadingOfFriends: (id) obj
{
    //webservice calls and results

    [self performSelectorOnMainThread:@selector(invokeRefreshAfterLoadingFriends:) 
                       withObject:nil 
                    waitUntilDone:YES];
}

- (void) invokeRefreshAfterLoadingFriends: (id) obj
{
    //this line is where is hangs
    [queue waitUntilAllOperationsAreFinished];

    //never gets here
    [self refresh: NO];
}

关于为什么第一个线程调用似乎永远不会结束的任何想法?

感谢您可以给马克的任何帮助

4

1 回答 1

2

在这里,您正在调用主线程上的一个方法,该方法等待被调用的方法完成(waitUntilDone:YES):

[self performSelectorOnMainThread:@selector(invokeRefreshAfterLoadingFriends:) 
                   withObject:nil 
                waitUntilDone:YES];

然后,您调用-invokeRefreshAfterLoadingFriends:which 保持主线程直到操作完成,因此该方法永远不会“完成”。从文档中-waitUntilAllOperationsAreFinished

调用时,此方法会阻塞当前线程并等待接收者的当前和排队操作完成执行。

结果,-invokeLoadingOfFriends:操作方法等待主线程的方法完成,这永远不会发生,因为您使用[queue waitUntilAllOperationsAreFinished].

尝试设置waitUntilDoneNO,看看这是否有助于操作完成。

于 2010-07-29T10:47:21.103 回答