通过unavailable宏来禁止调用某些属性方法
#import <Foundation/Foundation.h>
@interface MySingleton : NSObject
+(instancetype) sharedInstance;
// 外部调用将产生编译错误
+(instancetype) alloc __attribute__((unavailable("alloc not available, call sharedInstance instead")));
-(instancetype) init __attribute__((unavailable("init not available, call sharedInstance instead")));
+(instancetype) new __attribute__((unavailable("new not available, call sharedInstance instead")));
@end
#import "MySingleton.h"
//单例模式实现
@implementation MySingleton
//外部只能通过调用这个静态方法获得唯一的实例
+(instancetype) sharedInstance {
static dispatch_once_t pred;
static id shared = nil;
dispatch_once(&pred, ^{
shared = [[super alloc] initUniqueInstance];
});
return shared;
}
//生成唯一的实例
-(instancetype) initUniqueInstance {
return [super init];
}
@end