Swift中的单例定义个人感觉和Objective-C的单例有所不同,在之前,Objective-C的单例首先是定义一个static的类对象,然后通过GCD来确保只执行一次,但是在Swift的类中不允许有static的成员变量,虽然类中不允许有static的成员变量,但是结构体中是可以的有static的成员变量的,所以首先以Student类为实例:
首先定义个一个结构体
//定义一个名字叫做Inner的结构体
struct Inner{
static var m:Student?;//?表示 可能不存在
static var token:dispatch_once_t = 0;//默认为0,可以按住option点进去看一下开发文档,解释如下
/*!
* @typedef dispatch_once_t
*
* @abstract
* A predicate for use with dispatch_once(). It must be initialized to zero.//一个谓词,必须为0
* Note: static and global variables default to zero.//static(静态)和全局默认为0
public typealias dispatch_once_t = Int
*/
}
接下来的单例方法就和之前很像了,只不过Swift中没有Block代码块的概念,但是有闭包的概念,所以定义如下
//单例
static func shareInstance() -> Student
{
//与objc的一样,确保只执行一次
dispatch_once(&Inner.token) { () -> Void in
Inner.m = student();
}
return Inner.m!;
}
如果觉得上面这么写麻烦,当然也有很简单的写法,如下:
class Student
{
static private var onceToken : dispatch_once_t = 0
static private var shareObject : Student?
class func shareInstance() -> Student {
dispatch_once(&onceToken) {
shareObject = Student()
}
return shareObject!
}
}
用代码进行测试,如下
//获取两个单例对象(实际指向同一块内存)
var student1:Student = Student.shareInstance();
var student2:Student = Student.shareInstance();
//定义第一个单例对象的name
student1.name = "RunIntoLove";
print("student1.name = \(student1.name)");
print("student2.name = \(student2.name)");
//定义第二个单例对象的name
student2.name = "RunIntoLove----------";
print("student1.name = \(student1.name)");
print("student2.name = \(student2.name)");
student1.name = Optional("RunIntoLove")
student2.name = Optional("RunIntoLove")
student1.name = Optional("RunIntoLove----------")
student2.name = Optional("RunIntoLove----------")
Program ended with exit code: 0

5400

被折叠的 条评论
为什么被折叠?



