3

I want to create a singleton which disallows these methods in the .h file (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 redefine them in the @interface MyClass () section of the .m file in order to be able to use init internally?


I'm looking for something similar to when you create a readonly property on the header and you redefine it as readwrite on the implementation (but for __attribute__).

Like so:

// MyClass.h
@interface MyClass

@property (readonly) OtherClass *myThing;

@end

and

// MyClass.m
@interface MyClass ()

@property (readwrite) OtherClass *myThing;

@end
Community
  • 1
  • 1
Ricardo Sanchez-Saez
  • 9,466
  • 8
  • 53
  • 92

1 Answers1

0

This you can do only for 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 of

_sharedInstance = [[self alloc] init];

in the sharedInstance method compiler will give error that you put in .h file,i.e. init is not available.

I hope it will help.

Rajeev
  • 585
  • 3
  • 13