版权声明:本文为博主原创文章,未经博主允许不得转载。 https://cloud.tencent.com/developer/article/1338208
单例
单例:Singleton pattern。就是只有一个实例,不管实例化多少个对象,对象都是唯一的(可以通过打印其地址证明)。
下面就是一些单例的代码,不是很全,后面接触到新的还会继续补充。
1.普通创建单例的方法:
利用类方法创建单例,首先是类方法的声明(就是普通类方法的声明,不必多说)。
代码:
#import<Foundation/Foundation.h>
@interface StudentManager :NSObject
+(StudentManager *)shareInstance;
@end
重点是单例的创建,也就是这个类方法的实现。
代码:
#import"StudentManager.h"
staticStudentManager * student;
@implementation StudentManager
+(StudentManager *)shareInstance
{
if (student ==nil) {
student = [StudentManageralloc init];
}
returnstudent;
}
@end
这样单例就创建好了,当我们用这个类方法来创建对象的时候,哪怕是创建再多的对象得到的对象都是唯一的,也就是单例。至于为什么要用单例呢,大家可以上网区查查,有比较全面、详细的解释。一般当系统中希望某个类的对象只有一个的时候,我们一般都会用到单例。
2.利用dispatch创建单例:
也是利用了一个类方法,声明和前面的是一样的,就不在赘述了。
实现代码:
#import"StudentManager.h"
@implementation StudentManager
+(StudentManager *)shareInstance
{
staticStudentManager * studentManager;
staticdispatch_once_t oneToken;
dispatch_once(&oneToken, ^{
studentManager = [StudentManageralloc init];
});
return studentManager;
}
@end