Created
July 5, 2017 13:35
-
-
Save craigmarvelley/116215d73cfd46443b229db35381b2e9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- (NSMutableDictionary *)throttleActionHash | |
{ | |
NSMutableDictionary *throttleData = objc_getAssociatedObject(self, THROTTLE_ACTION_HASH_PROPERTY_KEY); | |
if (!throttleData) { | |
throttleData = [[NSMutableDictionary alloc] init]; | |
objc_setAssociatedObject(self, THROTTLE_ACTION_HASH_PROPERTY_KEY, throttleData, OBJC_ASSOCIATION_RETAIN); | |
} | |
return throttleData; | |
} | |
- (void)RateLimiting_throttle:(SEL)action duration:(NSTimeInterval)duration | |
{ | |
NSMutableDictionary *actionHash = [self throttleActionHash]; | |
NSDate *lastCalled = [actionHash objectForKey:NSStringFromSelector(action)]; | |
if (!lastCalled || ([[NSDate date] timeIntervalSinceDate:lastCalled]) >= duration) { | |
[actionHash setObject:[NSDate date] forKey:NSStringFromSelector(action)]; | |
__weak typeof(self) weakSelf = self; | |
IMP imp = [weakSelf methodForSelector:action]; | |
void (*func)(id, SEL) = (void *)imp; | |
func(weakSelf, action); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment