Skip to content

Instantly share code, notes, and snippets.

@craigmarvelley
Created July 5, 2017 13:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save craigmarvelley/116215d73cfd46443b229db35381b2e9 to your computer and use it in GitHub Desktop.
Save craigmarvelley/116215d73cfd46443b229db35381b2e9 to your computer and use it in GitHub Desktop.
- (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