如果我经常调用 setneedsdisplay,那么调用 drawrect 的频率是多少?这是为什么?

If I call setneedsdisplay frequently, how often will the drawrect be called? why is that?

在我的例子中,drawRect: 不会在每个 setNeedsDisplay 被调用后立即被调用。例如,我认为以下代码与我的情况相同。

for (int i = 0; i < 100; ++i)
{
    [self setNeedsDisplay];
}

来自documentation

When the actual content of your view changes, it is your responsibility to notify the system that your view needs to be redrawn. You do this by calling your view’s setNeedsDisplay or setNeedsDisplayInRect: method of the view. These methods let the system know that it should update the view during the next drawing cycle. Because it waits until the next drawing cycle to update the view, you can call these methods on multiple views to update them at the same time.

drawRect: 只会在绘制下一帧时及时调用,这意味着您的整个循环将导致 drawRect: 在下一次渲染迭代时仅被调用一次。这节省了不必要的计算,因为它避免了绘制永远不会显示在屏幕上的帧。它还允许您在代码的不同位置进行多项更改,每次都通知视图需要刷新,而不会降低性能,因为 调用 setNeedsDisplay 只告诉绘图系统重绘是下一帧需要;它不会强制立即呈现可能永远不会显示在屏幕上的帧。

setNeedsDisplay标记 视图需要再次显示。实际的绘图调用在主线程的下一个运行循环迭代中完成,一次。这允许绘图系统进行一些优化和 "combine" 重复调用 setNeedsDisplay.