美文网首页iOS开发iOS优化
iOS-检测UI主线程小工具

iOS-检测UI主线程小工具

作者: tljackyi | 来源:发表于2016-05-17 23:20 被阅读998次

在iOS开发中需要保证所有UI操作一定是在主线程进行,通过 hook UIView的-setNeedsLayout,-setNeedsDisplay,-setNeedsDisplayInRect三个方法,确保它们都是在主线程执行。

#import "UIView+NBUIKitMainThreadGuard.h"
#import <objc/runtime.h>

static inline void swizzling_exchangeMethod(Class clazz ,SEL originalSelector, SEL swizzledSelector){
    Method originalMethod = class_getInstanceMethod(clazz, originalSelector);
    Method swizzledMethod = class_getInstanceMethod(clazz, swizzledSelector);
    
    BOOL success = class_addMethod(clazz, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod));
    if (success) {
        class_replaceMethod(clazz, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
    } else {
        method_exchangeImplementations(originalMethod, swizzledMethod);
    }
}

@implementation UIView (NBUIKitMainThreadGuard)

+(void)load
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        SEL needsLayoutOriginalSelector = @selector(setNeedsLayout);
        SEL needsLayoutSwizzleSelector  = @selector(guard_setNeedsLayout);
        swizzling_exchangeMethod(self, needsLayoutOriginalSelector,needsLayoutSwizzleSelector);
        
        SEL needsDisplaOriginalSelector = @selector(setNeedsDisplay);
        SEL needsDisplaSwizzleSelector  = @selector(guard_setNeedsDisplay);
        swizzling_exchangeMethod(self, needsDisplaOriginalSelector,needsDisplaSwizzleSelector);
        
        SEL needsDisplayInRectOriginalSelector = @selector(setNeedsDisplayInRect:);
        SEL needsDisplayInRectSwizzleSelector  = @selector(guard_setNeedsDisplayInRect:);
        swizzling_exchangeMethod(self, needsDisplayInRectOriginalSelector,needsDisplayInRectSwizzleSelector);
        
    });
}

- (void)guard_setNeedsLayout
{
    [self UIMainThreadCheck];
    [self guard_setNeedsLayout];
}

- (void)guard_setNeedsDisplay
{
    [self UIMainThreadCheck];
    [self guard_setNeedsDisplay];
}


- (void)guard_setNeedsDisplayInRect:(CGRect)rect
{
    [self UIMainThreadCheck];
    [self guard_setNeedsDisplayInRect:rect];
}

- (void)UIMainThreadCheck
{
    NSString *desc = [NSString stringWithFormat:@"%@", self.class];
    NSAssert([NSThread isMainThread], desc);
}

@end


相关文章

网友评论

  • SpursGo:我有个问题,只hook这三个方法就能保证所有ui操作么
  • 捏捏你的脸:怎么使用呢? 楼主在么
    iOSDevVicky:最近看微信读书的blog,然后看到微信说的方法,看看别人的实现,就看到这篇文章.回复一下你.
    iOSDevVicky:虽然我不是作者,但是我给你说一下吧,这个不需要任何处理只要保证这个.h和.m文件在你的工程中就行了.
  • ae15c68cb7b8:好文,顶起

本文标题:iOS-检测UI主线程小工具

本文链接:https://www.haomeiwen.com/subject/nfairttx.html