OC和Swift单例的写法

一 、OC中单例的写法:1.普通单例的写法  2. 利用多线程来写单例

#pragma mark --- 普通单例写法----

+ (Manager *)shareInstance{

static Manager *manager = nil;

if (manager == nil) {

manager = [[Manager alloc] init];

}

return manager;

}

#pragma mark --- 多线程单例写法----

+ (Manager *)sharesInstance{

static Manager *manager = nil;

static dispatch_once_t onceToken;

dispatch_once(&onceToken, ^{

manager = [[Manager alloc] init];

});

return manager;

}

二、Swift中单例的写法

class SingleTon: NSObject {

var name:String?

//  swift单例第一种写法

/*

格式: static let 名字:类型 = {

let instance = 类型()

return instance

}()

*/

static let shareSingleTon:SingleTon = {

let instance = SingleTon()

return instance

}()

//  单例写法二

/*

格式:static let instance = 类名()

class func shareSingleTon()->返回值类型

{

return instance

}

*/

static let instance = SingleTon()

class func shareSingTon()->SingleTon {

return instance

}

}

//  Swift单例方法的调用

class ViewController: UIViewController {

override func viewDidLoad() {

super.viewDidLoad()

//  单例方法一的调用

let mod1 = SingleTon.shareSingleTon

mod1.name = "张三"

let mod2 = SingleTon.shareSingleTon

print("mod2.name = \(mod2.name!)")

let mod3 = SingleTon.shareSingleTon

print("mod3.name = \(mod3.name!)")

//  单例方法二的调用

let mode1 = SingleTon.shareSingTon()

mode1.name = "李四"

let mode2 = SingleTon.shareSingTon()

print("mode2.name = \(mode2.name!)")

let mode3 = SingleTon.shareSingTon()

print("mode3.name = \(mode3.name!)")

}

}

你可能感兴趣的:(OC和Swift单例的写法)