[NSOperation:主线程中的addsubview和慢度

问题描述 投票:5回答:1

我实现了以下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秒钟才能看到第一个“绘制”日志。

为什么会这样?通常来说,我该如何表现才能找出哪一行代码需要执行大量时间?

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

有时(例如,十分之一)(例如,十分之一),这样做会导致崩溃,因为我不应该从NSOperation调用addsubview,因为它不是线程安全的。所以我将其更改为:

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

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

为什么这么慢?

nsoperation drawrect nsoperationqueue
1个回答
5
投票

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

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

    [self createCustomViews];

    dispatch_async(main_queue, ^{

        [self addAnotherCustomViewToView];

    });
});
© www.soinside.com 2019 - 2024. All rights reserved.