美文网首页
swift 中的单例

swift 中的单例

作者: 90后的晨仔 | 来源:发表于2021-04-12 21:30 被阅读0次

今天忽然想写个单例不知道咋写了,所以想起来之前看的王巍 (onevcat). “Swifter - Swift 必备 Tips (第四版)。这本书中的写法,所以想想还是记录一下吧。
今天忽然想写个单例不知道咋写了,所以想想还是记录一下吧。

  • OC版本写法一(这种写法不算是太严谨)
@implementation MyPeter
+ (id)sharedManager {
    static MyPeter * staticInstance = nil;
    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{
        staticInstance = [[self alloc] init];
    });
    return staticInstance;
}
@end
  • OC版本写法二(推荐这种写法)
static MyPeter * staticInstance = nil;
@implementation MyPeter
+(MyPeter *)sharedManager{
    return [[self alloc] init];
}
- (instancetype)init{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        staticInstance = [super init];
    });
    return staticInstance;
}

+(instancetype)allocWithZone:(struct _NSZone *)zone{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        staticInstance = [super init];
    });
    return staticInstance;
}


- (nonnull id)copyWithZone:(nullable NSZone *)zone{
    return staticInstance;
}
-(nonnull id)mutableCopyWithZone:(nullable NSZone *)zone{
    return staticInstance;
}




@end
  • swift版本写法一(swift 1.2之前版本写法)
  class var shared : MyPeter {
          struct Static {
                static let sharedInstance : MyPeter = MyPeter()
            }
            return Static.sharedInstance
        }
  • swift版本写法二(swift 1.2之前版本写法)
private let sharedInstance = MyPeter()
class  MyPeter: NSObject {
 class var shared : MyPeter {
        return sharedInstance
    }
 
}
  • swift版本写法三(没有特殊要求推荐使用这种写法)
class MyPeter  {
    static let shared = MyPeter()
    private init() {}
}

相关文章

  • swift语法-14单例

    swift语法-14单例 OC中单例 Swift中单例 简写 Swift中最长用的方法

  • 单例模式的书写

    ARC OC 中的单例 根据OC单例 改写成 Swift 中的单例 OC调用swift,需要#import "单例...

  • Swift中的单例

    转战swift有几天了,接触到了swift中的单例,下面介绍一下swift中的单例: 仿照OC中的单例的写法,写一...

  • 单例

    内存中只有一个对象实例 提供一个全局访问点 OC中的单例 swift中的单例 swift改进过的单例

  • Swift 单例

    Swift中编写单例的正确方式

  • 单例

    普通的 GCD单例 swift单例

  • iOS - 单例创建

    Swift创建单例 代码如下:Swift5 对应OC创建单例

  • Swift单例模式

    Swift单例模式 单例模式 单例模式的作用是解决“应用中只有一个实例”的一类问题。在Cocoa Touch框架中...

  • iOS 单例

    Objective-C 单例宏 Swift 单例声明

  • 单例

    //单例 // Swift 1.2后,可以使用类变量 // Swift 1.2之前单例的写法 /* class M...

网友评论

      本文标题:swift 中的单例

      本文链接:https://www.haomeiwen.com/subject/worflltx.html