单例模式 in Objective-C
来源:互联网 发布:华泰证券mac版软件 编辑:程序博客网 时间:2024/05/29 02:44
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- 单例模式 in Objective-C
- Objective C--单例模式
- Objective C--单例模式
- Objective C 单例模式
- Objective C--单例模式
- Objective-C单例模式
- Objective C--单例模式
- Objective-C单例模式
- Objective-C 单例模式
- Objective-C 单例模式
- Objective-C:单例模式
- Objective-C 单例模式
- Objective C 中实现单例模式
- Objective C 实现Singleton(单例)模式.
- Objective-C实现单例模式
- Objective-C 设计模式之单例
- 【Objective-C】单例模式的实现
- Objective —C 单例模式 Singleton
- C++ 线程的创建,挂起,唤醒,终止
- block 语法(ios 5上所得) DCD与Block
- 函数调用过程栈帧变化详解
- C# wm_nchisttest(无标题窗体的移动方法)
- 做产品经理而不是功能经理
- 单例模式 in Objective-C
- ubuntu 安装 texlive 2013
- Cracking the coding interview--Q2.1
- 上班时候,老被腾讯弹出来的新闻打扰,很少烦恼,于是编写了一小程序,用于彻底解决这个问题,并代码开源,以防杀毒软件告诉你是病毒
- 基于MFC的插件应用程序设计与实现
- 查找单链表中倒数第k个结点
- 程序员面试题精选100题(19)-反转链表[数据结构]
- Linux 删除大量文件
- 51nod---无法表示的数