iOS单例写法

459 阅读1分钟

在.h文件中写一个类方法

+ (instancetype)sharedNetworking;

在.m文件中实现一下该类方法

+ (instancetype)sharedNetworking {
    static MSLNetworking * sharedNetworkingTool = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedNetworkingTool = [[self alloc] init];
    });
    
    return sharedNetworkingTool;
}

swift单例写法:

class MSLNetworking {
    static let sharedInstance = MSLNetworking()
    private init() {} //This prevents others from using the default '()' initializer for this class.
}

在使用该类的时候,既可以使用单例,也可以实例出非单例的对象来,使用更灵活.