iOS单例模式的实现
来源:互联网 发布:英语复读机软件 编辑:程序博客网 时间:2024/05/22 01:29
单例是指静态分配的实例,而 iphone sdk 中全是这种实例,例如
[UIApplication sharedApplication] 返回一个指向代表应用程序的单例对象的指针。[UIDevice currentDevice] 获取一个代表所有使用硬件平台的对象。
将类方法与单例相结合,便可以在程序的任何地方访问静态实例,而无需使用指向对象的指针或保存它的实例变量。创建类的唯一实例(普通单例)的函数示例:
//在很多时候,我们使用某个类的唯一实例。最常见的就是一个程序的主类,以下是以名为 RootViewController 创建的一个单例函数:
static RootViewController *sharedRootController = nil;
+(RootViewController *) sharedController{
@synchronized(self)
{
if (sharedRootController == nil)
{
sharedRootController = [[[self alloc] init] autorelease];
}
}
return sharedRootController;
}
+(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 singleton单例模式的实现
- iOS单例模式的实现
- iOS单例模式的实现
- iOS单例模式的实现
- iOS单例模式的实现
- iOS单例模式的实现
- iOS单例模式的实现
- iOS单例模式的实现
- iOS单例模式的实现
- iOS单例模式的实现
- ios单例模式的实现
- ios单例模式的实现
- iOS中的单例模式的实现
- iOS 单例模式的实现
- ios单例模式的实现
- iOS单例模式实现
- iOS 单例模式实现
- MONGODB在CENTOS下的安装
- OCP-1Z0-051-V9.02-131题
- HTML ContentType
- PHP linux服务器报错 PHP Warning: PHP Startup: Unable to load dynamic library '/usr/local/lib/php/的解决方法!
- 位运算(转自matrix67)
- iOS单例模式的实现
- java设计模式(二)—— 装饰、门面、享元、原型、状态、策略
- 竞速游戏任务系统设计
- C语言做图 书 信 息 管 理 系 统,大学的孩子们 福音在哪,这足够应付你们考试了
- 逻辑卷管理器--LVM
- OCP-1Z0-051-V9.02-132题
- netty的心跳检测实现
- C++中Const 修饰指针就近原则
- 自动收集和手工收集统计信息讲解