1. 程式人生 > >iOS 模仿蘋果編寫單例

iOS 模仿蘋果編寫單例

調用 with void obj can nal lin elf enc

#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 模仿蘋果編寫單例