防抖工具

有点类似NSTimer,取名叫HighFrequencyTriggerFilter,附上代码,头文件:

#import 

@interface HighFrequencyTriggerFilter : NSObject

/**
 无论是触发成功还是最后取消掉,该对象都会失效,需要重新创建

 @param delayTime 缓冲时间
 @param triggerHandler 成功触发后调用的block
 @return 返回可操作的对象
 */
+ (instancetype)filterWithDelayTime:(NSTimeInterval)delayTime triggerHandler:(void(^)())triggerHandler;

/**
 触发
 */
- (void)trigger;
/**
 取消
 */
- (void)cancel;

@end

执行文件:

#import "HighFrequencyTriggerFilter.h"

@interface HighFrequencyTriggerFilter ()

@property (nonatomic, assign) NSTimeInterval delayTime;
@property (nonatomic, copy) void (^triggerHandler)();
@property (nonatomic, strong) NSTimer *timer;

@end

@implementation HighFrequencyTriggerFilter

+ (instancetype)filterWithDelayTime:(NSTimeInterval)delayTime triggerHandler:(void(^)())triggerHandler {
    HighFrequencyTriggerFilter *filter = [HighFrequencyTriggerFilter new];
    filter.delayTime = delayTime;
    filter.triggerHandler = triggerHandler;
    return filter;
}

- (void)trigger {
    [self.timer invalidate];
    self.timer = nil;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:self.delayTime target:self selector:@selector(delayTrigger) userInfo:nil repeats:NO];
}

- (void)delayTrigger {
    if (self.triggerHandler) {
        self.triggerHandler();
    }
    [self cancel];
}

- (void)cancel {
    [self.timer invalidate];
    self.timer = nil;
    self.triggerHandler = nil;
}

@end

github地址:
https://github.com/guolingege/HighFrequencyTriggerFilter

你可能感兴趣的:(防抖工具)