Can you remove the __attribute__ by overriding a variable or method?
I want to create a singleton that disallows these methods in a file .h
(more details 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")));
Can I override them in the @interface MyClass ()
file section .m
to be able to use init internally?
I'm looking for something similar when you create a property readonly
in the header and you override it as readwrite
in the implementation (but for __attribute__
).
Same:
// MyClass.h
@interface MyClass
@property (readonly) OtherClass *myThing;
@end
and
// MyClass.m
@interface MyClass ()
@property (readwrite) OtherClass *myThing;
@end
source to share
This can only be done for the init method, not for alloc and new. What you can do is:
//MyClass.h
@interface MyClass : NSObject
- (instancetype) init __attribute__((unavailable("init not available, call sharedInstance instead")));
+(instancetype)sharedInstance;
@end
and
//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;
}
Also if you will use
_sharedInstance = [[MyClass alloc] init];
instead
_sharedInstance = [[self alloc] init];
in the compiler the sharedInstance method will throw the error you put in the .h file, i.e. init is not available.
Hope this helps.
source to share