NSOperation:在主线程中添加子视图和缓慢

时间:2012-05-07 19:21:56

标签: nsoperation drawrect nsoperationqueue

我已实施以下NSOperation,以绘制N自定义视图

- (void)main {

    for (int i=0; i<N; i++) {

       << Alloc and configure customView #i >>
       //(customView is a UIView with some drawing code in drawrect)

       [delegate.view addSubview:customView];

    }

    NSLog(@"Operation completed");
}

在customView的drawRect方法中我有

- (void)drawRect {

    <<Drawing code>>

    NSLog(@"Drawed");
    delegate.drawedViews++;

    if (delegate.drawedViews==VIEWS_NUMBER) {
        [delegate allViewsDrawn];
    }
}

因此代理人在绘制所有视图时都会收到通知。

问题是,在“操作完成”日志之后,我需要大约5秒才能看到第一个“绘制”日志。

为什么会这样?一般来说,我应该如何处理以找出执行这么多时间的代码行?

------编辑------

有时候(比如10次中的1次)我正在崩溃这样做,因为我不应该从NSOperation调用addsubview,因为它不是线程安全的。所以我改为

[delegate.view  performSelectorOnMainThread:@selector(addSubview:) withObject:customView waitUntilDone:NO];

现在我不再崩溃,但这个过程需要很长时间才能执行!比以前多5倍。

为什么这么慢?

1 个答案:

答案 0 :(得分:5)

为了使事情正常运作,我们需要忘记NSOperation并使用这个“技巧”

dispatch_queue_t main_queue = dispatch_get_main_queue();
dispatch_async(main_queue, ^{

    [self createCustomViews];

    dispatch_async(main_queue, ^{

        [self addAnotherCustomViewToView];

    });
});
相关问题