-
Notifications
You must be signed in to change notification settings - Fork 6
/
LVDebounce.m
90 lines (67 loc) · 2.85 KB
/
LVDebounce.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
//
// LVDebounce.m
// LayerVault
//
// Created by Kelly Sutton on 7/23/13.
// Copyright (c) 2013 LayerVault. Licensed under the MIT License.
//
#import "LVDebounce.h"
static NSMutableDictionary *timers = nil;
@implementation LVDebounce
+ (void)initialize {
if (self == [LVDebounce class]) {
timers = [NSMutableDictionary dictionary];
}
}
+ (void)fireAfter:(NSTimeInterval)seconds target:(id)target selector:(SEL)aSelector userInfo:(id)userInfo {
@synchronized(self) {
NSArray *eventKey = @[target, NSStringFromSelector(aSelector)];
if ([timers objectForKey:eventKey]) {
NSTimer *timer = [timers objectForKey:eventKey];
if ([timer respondsToSelector:@selector(invalidate)])
[timer invalidate];
[timers removeObjectForKey:eventKey];
}
[timers setObject:[NSTimer scheduledTimerWithTimeInterval:seconds target:target selector:aSelector userInfo:userInfo repeats:NO]
forKey:eventKey];
}
}
static NSString * const LVFlagForArgumentWiseDebouncer = @"LVFlagForArgumentWiseDebouncer";
+ (void)fireAfter:(NSTimeInterval)seconds target:(id)target selector:(SEL)aSelector withObject:(id)anArgument
{
if (!target || !aSelector) {
return;
}
@synchronized(self) {
NSMutableArray *eventKey = [NSMutableArray arrayWithArray:@[LVFlagForArgumentWiseDebouncer, target, NSStringFromSelector(aSelector)]];
if (anArgument) {
[eventKey addObject:anArgument];
}
if ([timers objectForKey:eventKey]) {
NSTimer *timer = [timers objectForKey:eventKey];
if ([timer respondsToSelector:@selector(invalidate)])
[timer invalidate];
[timers removeObjectForKey:eventKey];
}
NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithDictionary:@{@"target": target,
@"selector": NSStringFromSelector(aSelector)}];
if (anArgument)
{
[userInfo setObject:anArgument forKey:@"object"];
}
SEL targetSelector = @selector(handleArgumentWiseDebouncingWithUserInfo:);
[timers setObject:[NSTimer scheduledTimerWithTimeInterval:seconds target:[self class] selector:targetSelector userInfo:userInfo repeats:NO]
forKey:eventKey];
}
}
+ (void)handleArgumentWiseDebouncingWithUserInfo:(NSTimer *)timer {
NSDictionary *userInfo = timer.userInfo;
id target = userInfo[@"target"];
SEL selector = NSSelectorFromString(userInfo[@"selector"]);
id object = nil;
if (userInfo[@"object"]) {
object = userInfo[@"object"];
}
[target performSelector:selector withObject:object];
}
@end