首页 > 代码库 > iOS.常用设计模式.01.单例模式
iOS.常用设计模式.01.单例模式
使用单例模式的类:
UIApplication
UIAccelerometer
NSUserDefaults
NSNotificationCenter
NSFileManager
NSBundle等
Singleton.h
#import <Foundation/Foundation.h> @interface Singleton : NSObject // 始终返回同一个Singleton的指针 + (Singleton *)sharedManager; @property (strong,nonatomic) NSString *singletonData; @end
Singleton.m
#import "Singleton.h" @implementation Singleton @synthesize singletonData =http://www.mamicode.com/ _singletonData; static Singleton *shareManger = nil; /** 该方法采用了GCD(Grand Central Dispatch)技术,这是一种机遇C语言的多线程访问计数。 dispatch_once函数就是GCD提供的,它的作用是在整个应用程序生命周期中只执行一次代码块。 dispatch_once_t是GCD提供的结构体,使用时需要将GCD地址传给dispatch_once函数。 dispatch_once函数能够记录该代码快是否被调用过。 **/ + (Singleton *)sharedManager { static dispatch_once_t once; dispatch_once(&once, ^{ shareManger = [[self alloc] init]; }); return shareManger; } @end
SingleAppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { [Singleton sharedManager].singletonData = @"Singleton init"; NSBundle *bundle = [NSBundle mainBundle]; NSLog(@"bundle = %@",bundle); return YES; }
SingleViewController.m
- (void)viewDidLoad { [super viewDidLoad]; NSLog(@"viewDidLoad print : %@",[Singleton sharedManager].singletonData); NSBundle *bundle = [NSBundle mainBundle]; NSLog(@"bundle = %@",bundle); }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。