gpt4 book ai didi

iphone - 在 runloop 空闲时运行代码

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:45:06 24 4
gpt4 key购买 nike

我正在寻找类似于

的行为
[[NSNotificationQueue defaultQueue] enqueueNotification:not postingStyle:NSPostWhenIdle coalesceMask:NSNotificationCoalescingOnName|NSNotificationCoalescingOnSender forModes:nil];

但在不使用通知的情况下,以某种方式将选择器或 block 而不是通知加入队列。

至于我的动机(只是想看看这是否是一种合法的做法)。我向一个 View 添加了多个 subview ,显然没有人知道有多少,所以每次我添加一个 subview 时,我都必须通过调用 layoutIfNeeded 以特定方式布局 subview 来执行一些计算。现在,我在想,如果我只能在 runloop 空闲时调用该方法(以某种方式推迟调用并合并它),那么在它执行布局计算时所有 subview 都已经添加。希望它有意义。

-(void)layoutSubviews
{
[super layoutSubviews];


UIView* prevView = nil;
for (NSUInteger i=0; i<[self.subviews count]; i++) {
UIView* view = self.subviews[i];
CGFloat spacing = prevView!=nil?self.spacing:0;
view.topLeft = CGPointOffset(prevView.bottomLeft, spacing, 0);
prevView = view;
}

[self fitSubviews];
}

添加了我在 layoutSubview 方法中的代码。

最佳答案

对于一般性问题,最简单的解决方案如下:

- (void)setNeedsCustomTask
{
// cancel any previously scheduled call to perform the task
[NSObject
cancelPreviousPerformRequestsWithTarget:self
selector:@selector(doCustomTask)
object:nil];

// schedule a new call; because you've specified any delay
// at all this will be scheduled to occur in the future rather than
// right now and because you've specified a 0.0 delay it'll be
// as soon as possible in the future
[self performSelector:@selector(doCustomTask) withObject:nil afterDelay:0.0];
}

- (void)doCustomTask
{
NSLog(@"I am a custom task");
}

之所以可行,是因为 performSelector:withObject:afterDelay: 安排了将来对运行循环的调用。您还可以指定 inModes: 例如如果您想避免跟踪模式。

在取消和重新安排方面显然存在一些技术低效,而不是将标志放在手边,但它很整洁,因为您不需要明确地编码状态。所以我认为先做这件事是一个很好的过早优化论据。

关于iphone - 在 runloop 空闲时运行代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14857218/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com