Swift中的"单列"

本文介绍了Objective-C与Swift两种语言实现单例模式的方法。在Objective-C中使用GCD的dispatch_once确保线程安全初始化单例;而在Swift中通过定义静态常量实现单例,并提供获取单例对象的类方法。

我们现在来看看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())
    }
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值