代码之家  ›  专栏  ›  技术社区  ›  Ben Collins

NSOperationQueue似乎在完成时挂起了几秒钟

  •  1
  • Ben Collins  · 技术社区  · 16 年前

    我有一个自定义视图控制器,它实现了 UITableViewDataSource UITableViewDelegate 协议。当我加载表的数据时(在我的 viewDidLoad 方法),我创建 NSOperationQueue NSInvocationOperation 并将其添加到队列中。我吐出一个活动指示器 出口。

    用于该操作的方法结束活动指示器动画。

    编辑 以下是一个缩写版本:

    @implementation MyViewController
    @synthesize ...
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        self.opsQueue = [[NSOperationQueue alloc] init];
    
        NSInvocationOperation *aiStartOp = [[[NSInvocationOperation alloc]
                                               initWithTarget:self
                                                     selector:@selector(showActivityIndicators)
                                                       object:nil] autorelease];
        [self.opsQueue addOperation:aiStartOp];
    
        NSInvocationOperation *dataOp = [[[[NSInvicationOperation alloc] 
                                             initWithTarget:self
                                                   selector:@selector(dataUpdate)
                                                     object:nil] autorelease];
        [dataOp addDependency aiStartOp];
        [self.opsQueue addOperation:dataOp];
    
        NSInvicationOperation *aiStopOp = [[[NSInvicationOperation alloc]
                                              initWithTarget:self
                                                    selector:@selector(hideActivityIndicators)
                                                      object:nil] autorelease];
        [aiStopOp addDependency:dataOp];
        [self.opsQueue addOperation:aiStopOp];
    }
    
    /* other stuff */
    
    @end
    

    - (void)hideActivityIndicators {
        DLog(@"hiding activity indicator");
        self.portraitChartProgressView.hidden = YES;
        [self.portraitChartProgressIndicator stopAnimating];
    
        self.landscapeProgressView.hidden = NO;
        [self.landscapeProgressIndicator startAnimating];
    }
    

    我在日志中看到的是上面日志消息的输出,然后是5秒的暂停,最后是隐藏了指示器的视图。

    有什么想法吗?

    1 回复  |  直到 16 年前
        1
  •  3
  •   falconcreek    16 年前

    所有UI事件、绘图等都需要在主线程上执行。

    - (void)hideActivityIndicators {
    
        if (![NSThread isMainThread]) 
             [self performSelectorOnMainThread:@selector(hideActivityIndicators) withObject:nil waitUntilDone:NO];
    
        DLog(@"hiding activity indicator");
        self.portraitChartProgressView.hidden = YES;
        [self.portraitChartProgressIndicator stopAnimating];
    
        self.landscapeProgressView.hidden = NO;
        [self.landscapeProgressIndicator startAnimating];
    }
    

    “编辑”

    现在我仔细看了一下,有一件事您可能不需要做,那就是通过添加到 NSOperationQueue

    这个 TopSongs