Last active
August 29, 2015 14:09
-
-
Save maxchuquimia/9459d01eedc488ffe002 to your computer and use it in GitHub Desktop.
iOS - Handy way to run a code block once, based on dispatch_once()
This file contains 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
#import <Foundation/Foundation.h> | |
@interface NSUserDefaults (Extension) | |
/*! | |
* Associates a block of code with a token. If the token has not been used the code block will run immediately. | |
* | |
* @param token A token unique to the code block | |
* @param block A block of code to run | |
* | |
* @return TRUE if the code block was run | |
*/ | |
bool run_once(NSString *token, dispatch_block_t block); | |
/*! | |
* Resets a token. The code block associated with it will be run again next time run_once is called | |
* | |
* @param token The spent token | |
*/ | |
+ (void)resetToken:(NSString *)token; | |
/*! | |
* Checks if a code block with given token will be run. This does not spend the token | |
* | |
* @param token The token | |
* | |
* @return TRUE if the token is not spent | |
*/ | |
+ (BOOL)willRunWithToken:(NSString *)token; | |
@end |
This file contains 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
#import "NSUserDefaults+Extension.h" | |
@implementation NSUserDefaults (Extension) | |
bool run_once(NSString *token, dispatch_block_t block) | |
{ | |
if (!token) | |
{ | |
return FALSE; | |
} | |
NSString *identifier = [NSString stringWithFormat:@"defaults.run_once.%@", token]; | |
if (![[NSUserDefaults standardUserDefaults] boolForKey:identifier]) | |
{ | |
[[NSUserDefaults standardUserDefaults] setBool:TRUE forKey:identifier]; | |
[[NSUserDefaults standardUserDefaults] synchronize]; | |
block(); | |
return TRUE; | |
} | |
return FALSE; | |
} | |
+ (void)resetToken:(NSString *)token | |
{ | |
NSString *identifier = [NSString stringWithFormat:@"defaults.run_once.%@", token]; | |
[[NSUserDefaults standardUserDefaults] removeObjectForKey:identifier]; | |
[[NSUserDefaults standardUserDefaults] synchronize]; | |
} | |
+ (BOOL)willRunWithToken:(NSString *)token | |
{ | |
if (!token) | |
{ | |
return FALSE; | |
} | |
NSString *identifier = [NSString stringWithFormat:@"defaults.run_once.%@", token]; | |
return ![[NSUserDefaults standardUserDefaults] boolForKey:identifier]; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment