IOS 中的单例模式
来源:互联网 发布:网络餐饮新规 编辑:程序博客网 时间:2024/06/10 02:55
转自 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- iOS中的单例模式
- IOS中的单例模式
- IOS 中的单例模式
- iOS中的单例模式
- iOS中的单例模式
- iOS中的单例模式
- iOS中的单例模式
- iOS中的单例模式
- IOS中的单例模式
- IOS中的单例模式
- iOS中的单例模式
- iOS 中的单例模式
- iOS中的单例模式
- iOS中的单例模式
- ios中的单例模式
- iOS中的单例模式
- iOS中的单例模式
- iOS中的单例模式
- MYSQL版本:5.1.44-community
- MDSL记录仪的阵列
- 从文件 I/O 看 Linux 的虚拟文件系统
- 程序设计模式之单例模式
- linux内核概要说明
- IOS 中的单例模式
- The Boyer-Moore Majority Vote Algorithm
- Hp touchpad usb driver on android
- 利用devstack安装openstack以及neutron的配置等
- 李浣 我無愧乎
- android.view.InflateException: Binary XML file line #33: Error inflating class <unknown>
- Gamescom2014:中国游戏公司37.com进军西方海外市场
- IE inline-block bug 解决方法
- 堆排序