首页 > 代码库 > iOS 模仿苹果编写单例

iOS 模仿苹果编写单例

#import <Foundation/Foundation.h>

 @interface Person : NSObject

 +(instancetype)sharePerson;

 @end

 #import "Person.h"

 @implementation Person

 static Person *_instance = nil;

 +(void)load{

    _instance = [[self alloc] init];// 已进入就调用

}

 +(instancetype)sharePerson{

    return _instance;

}

 +(instancetype)alloc{

    if (_instance) { // 禁止调用alloc

     NSException *exception =    [NSException  exceptionWithName:NSInternalInconsistencyException reason:@"There can only be on Person instance" userInfo:@{}];

        [exception raise];// 抛出异常

    }

    return [super alloc];

}

 @end

iOS 模仿苹果编写单例