iOS单例模式
来源:互联网 发布:it技术书籍 编辑:程序博客网 时间:2024/05/29 10:43
单例设计模式。因为此模式经常引起争议,所以我想有必 要在此解释一下单例。
原则上,单例是在程序生命周期里只被实例化过一次的 类。为了确保这一点,我们利用类的一个静态方法来生成和访问对象。
因此, 你是通过以便利方法来访问某个类的单例对象的,而不是用 alloc/init或者静态autorelease初始化方法。
在很多时候,我们使用一个某个类的唯一实例。最常见的就是一个程序的主类。
以下是以名为 RootViewController 创建的一个单例函数:
static RootViewController*sharedRootController = nil;
+(RootViewController *) sharedController{
@synchronized(self){
if (sharedRootController == nil) {
sharedRootController = [[[self alloc] init] autorelease];(#add turorelease未必好,一般不用)
}
}
return singleController;
}
+(id) allocWithZone:(NSZone *)zone{
@synchronized(self){
if (sharedRootController == nil) {
sharedRootController = [super allocWithZone:zone];
return sharedRootController;
}
}
return nil;
}
代码说明:
1. synchronized 这个主要是考虑多线程的程序,这个指令可以将{ } 内的代码限制在一个线程执行,如果某个线程没有执行完,其他的线程如果需要执行就得等着。
2. 网上搜索的代码,好像有一个没有加入 autorelease ,我觉得应该需要加。因为如果调用的函数没有release 就麻烦了。(个人认为IOS 上的程序,对于创建用于函数返回值的,都应该考虑 autorelease)
3. allocWithZone 这个是重载的,因为这个是从制定的内存区域读取信息创建实例,所以如果需要的单例已经有了,就需要禁止修改当前单例。所以返回 nil
- iOS单例模式
- iOS 单例模式
- IOS 单例模式
- iOS 单例模式
- IOS单例模式
- ios单例模式
- iOS 单例模式
- iOS 单例模式
- IOS单例模式
- iOS 单例模式
- iOS 单例模式
- IOS 单例模式
- IOS---单例模式
- iOS--单例模式
- iOS 单例模式
- ios 单例模式
- iOS 单例模式
- IOS单例模式
- [转]嵌入式Web服务器
- C语言运算符优先级 详细列表
- 微软原版 windows server 2003 sp2 R2 系列下载分享
- 数据库缓存
- 算法,不改变正负数之间相对顺序重新排列数组.时间O(N),空间O(1)
- iOS单例模式
- 我在公司做的一个小游戏的总结感想
- 编写高效的Android代码
- How to detect and avoid memory and resources leaks in .NET applications()
- MySQL源码分析(1):主要模块及数据流
- 作为一个合格程序员每天该做的事
- 一些体会
- 杭电1005题
- shell 的If语句解析