到目前为止,这是我的策略:
我宣布了这个协议:
@protocol BGSuperSingletonProtocol <NSObject>
+(id) singleton1;
+(instancetype)singleton;
@end
然后我创建了一个所有 NSObject 都支持该协议的类别。但是,我不希望所有 NSObject 都支持该协议。我只是想要一些 NSObject 来做。所以我会将此标头插入 .m 文件而不是 .h 文件
#import "BGSuperSingletonProtocol.h"
@interface NSObject (singleton) <BGSuperSingletonProtocol>
@end
然后我写那个类的实现
#import "NSObject+singleton.h"
@implementation NSObject (singleton)
static NSMutableDictionary * allTheSingletons;
+(instancetype)singleton
{
return [self singleton1];
}
+(id) singleton1
{
NSString* className = NSStringFromClass([self class]);
if (!allTheSingletons)
{
allTheSingletons = NSMutableDictionary.dictionary;
}
id result = allTheSingletons[className];
//PO1(result);
if (result==nil)
{
result = [[[self class] alloc]init];
allTheSingletons[className]=result;
[result additionalInitialization];
}
return result;
}
-(void) additionalInitialization
{
}