setNeedsLayout如何工作?

Chr*_*orr 4 setter objective-c delay delayed-execution nsrunloop

我想知道Apple是如何-setNeedsLayout运作的.

我已经知道它比直接调用更有效-layoutSubviews,因为我可能需要在方法中执行两次.
这正是我所需要的:-setNeedsValidation视图控制器的一些自定义.
但是如何实现这样的功能呢?

Rob*_*ier 5

我无法确认Apple是否采用这种方式,但这是一种方法来做你想要的,并且可能类似于setNeedsLayout实现的方式.我没有测试过这个(或者甚至编译过它),但它应该知道如何将问题作为一个类别进行攻击UIViewController.像UIKit一样,这完全是线程不安全的.

static NSMutableSet sViewControllersNeedingValidation = nil;
static BOOL sWillValidate = NO;

@implementation UIViewController (Validation)
+ (void)load {
  sViewControllersNeedingValidation = [[NSMutableSet alloc] init];
}

- (void)setNeedsValidation {
  [sViewControllersNeedingValidation addObject:self];

  if (! sWillValidate) {
    sWillValidate = YES;
    // Schedule for the next event loop
    [[self class] performSelector:@selector(dispatchValidation) withObject:nil afterDelay:0];
  }
}

+ (void)dispatchValidation {
  sWillValidate = NO;
  // The copy here is in case any of the validations call setNeedsValidation.
  NSSet *controllers = [sViewControllersNeedingValidation copy];
  [sViewControllersNeedingValidation removeAllObjects];
  [controllers makeObjectsPerformSelector:@selector(validate)];
  [controllers release];
}

- (void)validate {
  // Empty default implementation
}
Run Code Online (Sandbox Code Playgroud)