[code review] Action Blocker : bloquer une action s'il vient d'être lancée.

colas_colas_ Membre
octobre 2015 modifié dans Objective-C, Swift, C, C++ #1

Bonjour,


 


je viens d'écrire une petite classe qui bloque une action si celle-ci vient d'être lancée. Qu'en pensez-vous ? Voyez-vous des points à  améliorer ?


 


Merci !


 


https://github.com/colasjojo/CBDActionBlocker


 


.h



#import <Foundation/Foundation.h>

@interface CBDActionBlocker : NSObject

/**
This methods fires the selector unless it is blocked.
If the method is blocked, depending on the value of `resetBlocking`,
we reset the blocker to 0 or not.
*/
+ (void)fireTarget:(id)target selector:(SEL)aSelector blockFiresDuring:(NSTimeInterval)seconds resetBlocking:(BOOL)resetBlocking;

@end

.m



#import "CBDActionBlocker.h"

static NSMutableDictionary *timestamps = nil;

@implementation CBDActionBlocker

+ (void)initialize
{
if (self == [CBDActionBlocker class]
&&
!timestamps)
{
timestamps = [NSMutableDictionary dictionary];
}
}

+ (void)fireTarget:(id)target selector:(SEL)aSelector blockFiresDuring:(NSTimeInterval)seconds resetBlocking:(BOOL)resetBlocking
{
@synchronized(self)
{
NSTimeInterval currentTimestamp = [self currentTimestamp];

NSArray *eventKey = @[;target, NSStringFromSelector(aSelector)];
NSNumber *timestamp = [timestamps objectForKey:eventKey];

if (timestamp) {

if ([timestamp doubleValue] < currentTimestamp)
{
if (resetBlocking)
{
[self registerTimestamp:currentTimestamp+seconds forKey:eventKey];
}
}
else
{
[self fireTarget:target selector:aSelector];
[self registerTimestamp:currentTimestamp+seconds
forKey:eventKey];
}
}

[self fireTarget:target selector:aSelector];
[self registerTimestamp:currentTimestamp+seconds forKey:eventKey];
}
}



+ (void)fireTarget:(id)target selector:(SEL)aSelector
{
// We suppress the warning
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
[target performSelector:aSelector];
#pragma clang diagnostic pop
}


+ (void)registerTimestamp:(NSTimeInterval)timestamp forKey:(id)key
{
[timestamps setObject:@(timestamp)
forKey:key];
}


+ (NSTimeInterval)currentTimestamp
{
return [[NSDate date] timeIntervalSinceReferenceDate];
}

@end


Réponses

  • AliGatorAliGator Membre, Modérateur
    Pourquoi ne pas plutôt proposer une API avec des blocks ? Les target-action c'est un peu has-been pour ce genre de fonctionnalité ^^
  • colas_colas_ Membre
    octobre 2015 modifié #3

    L'avantage c'est qu'il est facile d'identifier quelle action a été lancée : on connaà®t le target et le selecteur.


    (on a besoin de mettre des flags sur : "cette action a déjà  été lancée il y a 10s").


     


    Pour les blocks, ça va être plus difficile... Je doute que isEqualTo soit implémenté sur les blocks :P


Connectez-vous ou Inscrivez-vous pour répondre.