单例模式是一种常用的软件设计模式。在它的核心结构中只包含一个被称为单例类的特殊类。通过单例模式可以保证系统中一个类只有一个实例而且该实例易于外界访问。
第二、在IOS中使用单例模式的情况
1.如果说创建一个对象会耗费很多系统资源,那么此时采用单例模式,因为只需要一个实例,会节省alloc的时间
2.在IOS开发中,如果很多模块都要使用同一个变量,此时如果把该变量放入单例类,则所有访问该变量的调用变得很容易,否则,只能通过一个模块传递给另外一个模块,这样增加了风险和复杂度
第三、创建单例模式的基本步骤
1.声明一个单例对象的静态实例,并初始化为nil
2.声明一个类的工厂方法,生成一个该类的实例,并且只会生成一个
3.覆盖allcoWithZone方法,确保用户在alloc 时,不会产生一个多余的对象
4.实现NSCopying协议,覆盖release,autorelease,retain,retainCount方法,以确保只有一个实例化对象
5.在多线程的环境中,注意使用@synchronized关键字
单例的实现如下:
新建一个类继承于NSObject
ShareInstance.h
@interface Sharelnstance : NSObject
@property (assign, nonatomic) NSInteger loginState; // .h中声明了容器类的变量,则必须在.m中的初始化里进行初始化(例如:数组,字典,集合)
@property (retain, nonatomic) NSMutableArray *array;
+ (Sharelnstance *)shareInstance;
@end
shareInstance.m
#import "Sharelnstance.h"
// 单例特性: 1.只初始化一次, 且内存唯一(不管创建多少次,永远得到的都是第一次创建后的对象)
// 2.不释放, 在第一次创建成功后, 知道程序退出, 内存才被系统回收
static Sharelnstance *share = nil;
@implementation Sharelnstance
// 通过类方法来创建对象,在方法内部避免多次调用alloc
+ (Sharelnstance *)shareInstance{
// 单例线程安全(两种书写方法)
// 第一种:
@synchronized(self){
if (!share) {
share = [[Sharelnstance alloc] init];
share.array = [NSMutableArray array];
}
}
// 第二种:
// static dispatch_once_t once;
// dispatch_once(&once, ^{
// share = [[Sharelnstance alloc] init];
// });
return share;
}
@end
#import "MainViewController.h"
#import "Sharelnstance.h"
@interface MainViewController ()
@end
@implementation MainViewController
- (void)dealloc{
[super dealloc];
}
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
}
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.view.backgroundColor = [UIColor whiteColor];
// 单例:
// 内存唯一
// 只初始化一次,永远不释放
// 在内存里面
Sharelnstance *share = [Sharelnstance shareInstance];
NSLog(@"%ld", share.loginState);
}
AppDelegate.m
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
_window.backgroundColor = [UIColor whiteColor];
[_window makeKeyAndVisible];
[_window release];
Sharelnstance *share = [Sharelnstance shareInstance];
share.loginState = 10;
MainViewController *main = [[MainViewController alloc] init];
UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:main];
[_window setRootViewController:nav];
[main release];
[nav release];