iOS开发中-单例的讲解
2016-09-09 10:09
232 查看
1.单例的作用
单例,即是在整个项目中,这个类的对象只能被初始化一次。它的这种特性,可以广泛应用于某些需要全局共享的资源中,比如管理类,引擎类,也可以通过单例来实现传值。UIApplication、NSUserDefaults等都是iOS中的系统单例。首先来个线程不安全的写法
static SingleCase *manager = nil;
(SingleCase *)defaultManager {
if (!manager){
SingleCase = [[self alloc] init];
return manager;
}
}
再来来个苹果官方的写法
[cpp] view plaincopy
+ (AccountManager *)sharedManager { static AccountManager *sharedAccountManagerInstance = nil; static dispatch_once_t predicate; dispatch_once(&predicate, ^{ sharedAccountManagerInstance = [[self alloc] init]; }); return sharedAccountManagerInstance; }
该写法具有以下几个特性:
1 线程安全。
2 满足静态分析器的要求。
3 兼容了ARC
下面是官方文档介绍对上面的代码介绍:
dispatch_once
Executes a block object once and only once for the lifetime of an application.
void dispatch_once(
dispatch_once_t *predicate, dispatch_block_t block);
Parameters
predicate
A pointer to a dispatch_once_t structure that is used to test whether the block has completed or not.
block
The block object to execute once.
Discussion
This function is useful for initialization of global data (singletons) in an application. Always call this function before using or testing any variables that are initialized by the block.
If called simultaneously from multiple threads, this function waits synchronously until the block has completed.
The predicate must point to a variable stored in global or static scope. The result of using a predicate with automatic or dynamic storage is undefined.
Availability
Available in iOS 4.0 and later.
Declared In
dispatch/once.h
单例的使用比如在我们多人开发中在整个应用程序各个地方都要用户的数据进行临时存储,在一定程度程度上提高了工作效率,避免重覆代码!
相关文章推荐
- 【iOS-Cocos2d游戏开发之九】讲解CCSpriteBatchNode与TP工具的".pvr.ccz",".plist"共用的终极精灵优化及注意事项!
- 【iOS-Cocos2d游戏开发之六】对触屏事件追加讲解,解决无法触发ccTouchMoved事件[重要!]
- IOS开发之UITableView 详细讲解
- IOS 开发之 CocoaPods讲解
- 0天掌握iOS开发之Day2 - 内存管理 (给学生讲解的课件,总结的不错)
- 【iOS-Cocos2d游戏开发之六】对触屏事件追加讲解,解决无法触发ccTouchMoved事件[重要!]
- IOS学习笔记(十二)之IOS开发之表视图(UITableView)的讲解与使用(二)
- (转)【iOS-cocos2d-X 游戏开发之十】自定义CCSprite/Layer/CCNode及静态类模版&自定义类细节说明&Cocos2dx触屏事件讲解
- 【iOS-Cocos2d游戏开发之九】讲解CCSpriteBatchNode与TP工具的".pvr.ccz",".plist"共用的终极精灵优化及注意事项!
- 移动应用开发(IOS/android等)中一个通用的图片缓存方案讲解
- 【iOS-Cocos2d游戏开发之九】讲解CCSpriteBatchNode与TP工具的”.pvr.ccz”,”.plist”共用的终极精灵优化及注意事项!
- 【iOS-Cocos2d游戏开发之九】讲解CCSpriteBatchNode与TP工具的".pvr.ccz",".plist"共用的终极精灵优化及注意事项!
- 【iOS-cocos2d-X 游戏开发之十】自定义各类模版&触屏事件讲解! 推荐
- 【iOS-cocos2d-X 游戏开发之十三】详细讲解在Xcode中利用预编译并通过Jni调用Android的Java层代码(cocos2dx里访问调用Android函数)!
- ios开发入门- xcode开发工具使用讲解
- 【iOS-Cocos2d游戏开发之九】讲解CCSpriteBatchNode与TP工具的".pvr.ccz",".plist"共用的终极精灵优化及注意事项!
- 【iOS-Cocos2d游戏开发之九】讲解CCSpriteBatchNode与TP工具的".pvr.ccz",".plist"共用的终极精灵优化及注意事项!
- 【无限互联】iOS开发视频教程— 2.9 iPhone开发之作业讲解
- [置顶] IOS 开发之 CocoaPods讲解
- iOS开发 Object-C ARC模式讲解