【问题标题】:Can you remove an __attribute__ by redefining a variable or method?您可以通过重新定义变量或方法来删除 __attribute__ 吗?
【发布时间】:2014-08-04 10:56:28
【问题描述】:

我想在.h 文件中创建一个不允许这些方法的单例(更多详细信息here):

+ (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")));

我可以在.m 文件的@interface MyClass () 部分重新定义它们以便能够在内部使用init 吗?


我正在寻找类似于在标题上创建 readonly 属性并在实现中将其重新定义为 readwrite 的内容(但对于 __attribute__)。

像这样:

// MyClass.h
@interface MyClass

@property (readonly) OtherClass *myThing;

@end

// MyClass.m
@interface MyClass ()

@property (readwrite) OtherClass *myThing;

@end

【问题讨论】:

    标签: ios objective-c singleton clang


    【解决方案1】:

    您只能对 init 方法执行此操作,而不能对 alloc 和 new 执行此操作。你可以做的是:

    //MyClass.h
    @interface MyClass : NSObject
    
    - (instancetype) init __attribute__((unavailable("init not available, call sharedInstance instead")));
    
    +(instancetype)sharedInstance;
    
    @end
    

    //MyClass.m
    @implementation MyClass
    
    +(instancetype)sharedInstance
    {
        static MyClass *_sharedInstance;
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            _sharedInstance = [[self alloc] init];
        });
        return _sharedInstance;
    }
    
    
    -(instancetype)init
    {
        if (self=[super init]) {
    
        }
        return self;
    }
    

    如果你会使用

    _sharedInstance = [[MyClass alloc] init];
    

    而不是

    _sharedInstance = [[self alloc] init];
    

    在 sharedInstance 方法编译器中会给出您放入 .h 文件的错误,即初始化不可用。

    我希望它会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-28
      • 2018-08-13
      • 1970-01-01
      • 2011-01-22
      • 1970-01-01
      • 2021-07-22
      • 1970-01-01
      相关资源
      最近更新 更多