Singletons in Objective-C
来源:互联网 发布:c windows system32 编辑:程序博客网 时间:2024/05/02 06:40
from:http://www.galloway.me.uk/tutorials/singleton-classes/
Singletons in Objective-C
One of my most used design patterns when developing for iOS is the singleton pattern. It’s an extremely powerful way to share data between different parts of code without having to pass the data around manually. More about the singleton pattern and other patterns can be found in this excellent book:
Background
Singleton classes are an important concept to understand because they exhibit an extremely useful design pattern. This idea is used throughout the iPhone SDK, for example, UIApplication has a method called sharedApplication which when called from anywhere will return the UIApplication instance which relates to the currently running application.
How to implement
You can implement a singleton class in Objective-C using the following code:
MyManager.hMyManager.mWhat this does is it defines a static variable (but only global to this translation unit)) called sharedMyManager
which is then initialised once and only once in sharedManager
. The way we ensure that it’s only created once is by using the dispatch_once
method from Grand Central Dispatch (GCD). This is thread safe and handled entirely by the OS for you so that you don’t have to worry about it at all.
However, if you would rather not use GCD then you should use the following code for sharedManager
:
Then you can reference the singleton from anywhere by calling the following function:
MyManager *sharedManager = [MyManager sharedManager];
I’ve used this extensively throughout my code for things such as creating a singleton to handle CoreLocation or CoreData functions.
Non-ARC code
Not that I recommend it, but if you are not using Automatic Reference Counting (ARC), then you should use the following code:
MyManager.h non-ARC- Singletons in Objective-C
- Singletons in Objective-C
- Objective C & iOS Weak Singletons
- Objective-C中单例模式(Singletons)的实现
- Objective-C中单例模式(Singletons)的实现
- Singletons
- JSON in objective c
- Protocol in Objective-C
- selector in Objective-C
- NS_BLOCK_ASSERTIONS in Objective-C
- Categories in Objective-C
- Delegation in Objective-C
- Protocol in Objective-C
- Constants in Objective C
- WebSocket in Objective-C
- Protocol in Objective-C
- Singletons vs. Application Context in Android?
- Singletons in Cocoa, are they evil?
- DedeCMS V5.7使用session_register()在PHP5.4以上无法登录后台,页面无显示
- [中英文对照]android Designing for TV(三) ------ Handling Features Not Supported on TV 在TV上处理不支持的功能
- 嵌入式Linux之我行——S3C2440上LCD驱动(FrameBuffer)实例开发讲解(一) .
- 如何做好基层管理者(二)
- Keil MDK编译器(V4.03)与J-LINK使用
- Singletons in Objective-C
- C/C++中判断某一文件或目录是否存在
- Eclipse ADT配置CVS
- 升级 Windiows 2012 引起 MDT 的两个路径错误
- 爱立信2013暑期实习项目 历程
- GCM的Push功能调查汇总
- 设计模式六大原则(4):接口隔离原则
- SqlServer和Oracle中一些常用的sql语句3 行列转换
- DHL解决起来很容易,联系起来很难