您的位置:首页 > 移动开发 > Objective-C

Objective-C:禁止调用方法

2015-10-08 11:02 337 查看

通过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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: