两种方法创建单例

方法一

//

//  Manager.m

//  test

//

//  Created by zmx on 16/1/9.

//  Copyright © 2016 zmx. All rights reserved.

//


#import "Manager.h"


static Manager *manager;


@implementation Manager


+ (instancetype)sharedManager {

    if (manager ==nil) {

        manager = [[selfalloc] init];

    }

    returnmanager;

}


+ (instancetype)allocWithZone:(struct_NSZone *)zone {

    if (manager ==nil) {

        manager = [superallocWithZone:zone];

    }

    returnmanager;

}


@end


方法二  使用gcd的dispatch_once,iOS4以上

//

//  Manager.m

//  test

//

//  Created by zmx on 16/1/9.

//  Copyright © 2016 zmx. All rights reserved.

//


#import "Manager.h"


static Manager *manager;


@implementation Manager


+ (instancetype)sharedManager {

    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{

        manager = [[selfalloc] init];

    });

    returnmanager;

}


+ (instancetype)allocWithZone:(struct_NSZone *)zone {

    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{

        manager = [superallocWithZone:zone];

    });

    returnmanager;

}


@end


完善的方案详见http://blog.csdn.net/baidu_25845567/article/details/50706840

你可能感兴趣的:(iOS)