设计根据标示符全局只运行一次的类
全局只运行一次的代码,第一个想到的绝对是dispatch_once,这是不二的选择嘛,dispatch_once还是线程安全的.
这里我将提供一种非线程安全但也可以使用的全局只运行一次的代码,设计很简单:
现在提供类如下:
StaticFlag.h + StaticFlag.m
// // StaticFlag.h // Static // // Copyright (c) 2014年 Y.X. All rights reserved. // #import <Foundation/Foundation.h> typedef void (^StaticFlagBlock)(); @interface StaticFlag : NSObject + (void)flag:(NSString *)flag class:(Class)objectClass firstTime:(StaticFlagBlock)firstTime otherTimes:(StaticFlagBlock)otherTimes; @end
// // StaticFlag.m // Static // // Copyright (c) 2014年 Y.X. All rights reserved. // #import "StaticFlag.h" static NSMutableDictionary *flagDictionary = nil; @implementation StaticFlag + (void)initialize { if (self == [StaticFlag class]) { flagDictionary = [NSMutableDictionary new]; } } + (void)flag:(NSString *)flag class:(Class)objectClass firstTime:(StaticFlagBlock)firstTime otherTimes:(StaticFlagBlock)otherTimes { NSString *str = [NSStringFromClass(objectClass) stringByAppendingString:flag]; NSLog(@"%@", str); if ([flagDictionary valueForKey:str] == nil) { [flagDictionary setObject:@"HAVE" forKey:str]; firstTime(); } else { otherTimes(); } } @end
使用情况:
// // AppDelegate.m // OnlyOne // // Copyright (c) 2014年 Y.X. All rights reserved. // #import "AppDelegate.h" #import "StaticFlag.h" #define FLAG @"YouXianMing" @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { [StaticFlag flag:FLAG class:[AppDelegate class] firstTime:^{ NSLog(@"第一次"); } otherTimes:^{ NSLog(@"第二次"); }]; [StaticFlag flag:FLAG class:[AppDelegate class] firstTime:^{ NSLog(@"第一次"); } otherTimes:^{ NSLog(@"第二次"); }]; return YES; } @end