我们现在来看看OC中的单列
//
// NetWorkTools.h
#import <Foundation/Foundation.h>
@interface NetWorkTools : NSObject
+ (instancetype)shareNetWorkTools;
@end
//
// NetWorkTools.m
#import "NetWorkTools.h"
@implementation NetWorkTools
+ (instancetype)shareNetWorkTools
{
static id instance;
static dispatch_once_t onceToken;
// onceToken默认等于0,如果是0就会执行block
dispatch_once(&onceToken, ^{
instance = [[self alloc] init];
});
return instance;
}
@end
OC中获取单列对象:
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
NSLog(@"%@",[NetWorkTools shareNetWorkTools]);
NSLog(@"%@",[NetWorkTools shareNetWorkTools]);
// 上面打印内存地址相同
}
2.接下来我们看看Swift中的单列
//
// NetWorkTools.swift
// Swift中的单列
import UIKit
class NetWorkTools: NSObject {
// 定义一个静态常量
static let instance:NetWorkTools = NetWorkTools()
// 用于获取单列对象的类方法
class func sharedNetWorkTools() -> NetWorkTools {
return instance
}
}
获取单列对象:
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
print(NetWorkTools.sharedNetWorkTools())
print(NetWorkTools.sharedNetWorkTools())
}
本文介绍了Objective-C与Swift两种语言实现单例模式的方法。在Objective-C中使用GCD的dispatch_once确保线程安全初始化单例;而在Swift中通过定义静态常量实现单例,并提供获取单例对象的类方法。
5405

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



