Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: d7beac5e39
Fetching contributors…

Cannot retrieve contributors at this time

file 56 lines (43 sloc) 1.177 kb
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
//
// SSRateLimit.m
// SSToolkit
//
// Created by Sam Soffes on 4/9/12.
// Copyright (c) 2012 Sam Soffes. All rights reserved.
//

#import "SSRateLimit.h"

@interface SSRateLimit ()
+ (NSMutableDictionary *)_dictionary;
@end

@implementation SSRateLimit

+ (BOOL)executeBlock:(void(^)(void))block name:(NSString *)name limit:(NSTimeInterval)limit {
// Prevent a nil block
if (!block) {
return NO;
}

// Lookup last executed
NSMutableDictionary *dictionary = [self _dictionary];
NSDate *last = [dictionary objectForKey:name];
NSTimeInterval timeInterval = [last timeIntervalSinceNow];

// If last excuted is less than the limit, don't execute
if (timeInterval < 0 && fabs(timeInterval) < limit) {
return NO;
}

// Execute
block();
[dictionary setObject:[NSDate date] forKey:name];
return YES;
}


+ (void)resetLimitForName:(NSString *)name {
[[self _dictionary] removeObjectForKey:name];
}


#pragma mark - Private

+ (NSMutableDictionary *)_dictionary {
static NSMutableDictionary *dictionary = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
dictionary = [[NSMutableDictionary alloc] init];
});
return dictionary;
}

@end
Something went wrong with that request. Please try again.