OC
#import <Foundation/Foundation.h>
@interface Student : NSObject
//获取单例对象的第二种方式
+ (instancetype)shareInstance;
@end
#import "Student.h"
@implementation Student
//使用GCD的方式实现单例
//Apple推荐的方式
+ (instancetype)shareInstance {
static Student *instance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
instance = [[Student alloc] init];
});
return instance;
}
@end
Swift
import UIKit
//自己使用GCD实现一个单例
class Singleton: NSObject {
class var sharedInstance: Singleton {
struct Static {
static var onceToken: dispatch_once_t = 0
static var myInstance: Singleton?
}
dispatch_once(&Static.onceToken) {
Static.myInstance = Singleton()
}
return Static.myInstance!
}
}