单例的意思就是唯一一个实例,它可以确保这个实例自行初始化并向整个系统提供这个实例,这个类称为单例类。
1、单例模式的要点:
一是某个类只能有一个实例。
二是它必须自行创建这个实例。
三是它必须自行向整个系统提供这个实例。
2、优点:
实例控制:Singleton会阻止其他对象实例化自己的Singleton对象的副本,从而确保所有的对象都访问唯一实例。
灵活性:因为类控制了实例化的过程,所以类可以更加灵活地修改实例化过程。
ios sdk中有很多这种实例,例如:[UIApplication sharedApplication]返回一个指向代表应用程序的单例对象指针。
3、ios中的单例
在object-c中要实现一个单例类,需要下面两个步骤:
一、构建一个静态实例,然后设置nil;
二、实现一个类方法,检查上面声明的静态实例是否为nil。如果是,则新建单例类唯一的实例并返回,如果不为nil,则返回这个实例本身。
以下为创建一个单例类:
<span style="font-size:14px;">#import <Foundation/Foundation.h>
@interface appStatus : NSObject
@property(nonatomic,retain)NSString *contextStr;
+(appStatus *)getInstance;
@end</span>
<span style="font-size:14px;">#import "appStatus.h"
@implementation appStatus
static appStatus *_instance=nil;
+(appStatus *)getInstance{
if(_instance==nil) {
_instance=[[super alloc]init];
}
return _instance;
}
-(id)init
{
if(self=[super init])
{
self.contextStr=[[NSString alloc]init];
}
return self;
}
@end</span>