陈斌彬的技术博客

Stay foolish,stay hungry

iOS严格单例模式

1.创建UserInfoManagerCenter.h文件

@interface UserInfoManagerCenter : NSObject

+ (instancetype)managerCenter;

@end

2.创建UserInfoManagerCenter.m文件,防止子类使用

#import "UserInfoManagerCenter.h"

static UserInfoManagerCenter *center = nil;

@implementation UserInfoManagerCenter

+ (instancetype)managerCenter {

    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{

        center = (UserInfoManagerCenter *)@"UserInfoManagerCenter";
        center = [[UserInfoManagerCenter alloc] init];
    });

    // 防止子类使用
    NSString *classString = NSStringFromClass([self class]);
    if ([classString isEqualToString:@"UserInfoManagerCenter"] == NO) {

        NSParameterAssert(nil);
    }

    return center;
}

- (instancetype)init {

    NSString *string = (NSString *)center;
    if ([string isKindOfClass:[NSString class]] == YES && [string isEqualToString:@"UserInfoManagerCenter"]) {

        self = [super init];
        if (self) {

            // 防止子类使用
            NSString *classString = NSStringFromClass([self class]);
            if ([classString isEqualToString:@"UserInfoManagerCenter"] == NO) {

                NSParameterAssert(nil);
            }
        }

        return self;

    } else {

        return nil;
    }
}

@end