Singleton in iOS Objective C doesn't prevent more than one instance

后端 未结 9 1569
长情又很酷
长情又很酷 2020-11-29 08:53

I know there are several threads on this, but none answer my questions.

I\'ve implemented my singleton class like this (being aware of the controversy about singleto

9条回答
  •  悲&欢浪女
    2020-11-29 09:25

    With objective-c, you can prevent your singleton class to create more than one object. You can prevent alloc and init call with your singleton class.

    #import 
    
    @interface SingletonClass : NSObject
    
    + (id) sharedInstance;
    - (void) someMethodCall;
    - (instancetype) init __attribute__((unavailable("Use +[SingletonClass sharedInstance] instead")));
    + (instancetype) new __attribute__ ((unavailable("Use +[SingletonClass sharedInstance] instead")));
    
    @end
    
    
    #import "SingletonClass.h"
    
    @implementation SingletonClass
    
    + (id) sharedInstance{
        static SingletonClass * sharedObject = nil;
        static dispatch_once_t onceToken;
    
        dispatch_once(&onceToken, ^{
            sharedObject = [[self alloc] initPrivate];
        });
    
        return sharedObject;
    }
    
    - (instancetype)init {
        @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"You can't override the init call in class %@", NSStringFromClass([self class])] userInfo:nil];
    }
    
    - (instancetype)initPrivate {
        if (self = [super init]) {
    
        }
        return self;
    }
    
    
    - (void) someMethodCall{
        NSLog(@"Method Call");
    }
    
    @end
    

    1# If you will try to call init or new methods on SingletonClass, then these methods would not be available to call.

    2# If you comment out mentioned below methods in header file and try to call the init on SingletonClass method then app will be crashed with reason "You can't override the init call in class SingletonClass".

       - (instancetype) init __attribute__((unavailable("Use +[SingletonClass sharedInstance] instead")));
       + (instancetype) new __attribute__ ((unavailable("Use +[SingletonClass sharedInstance] instead")));
    

    Just use this code to create single object to Singleton Pattern and prevent alloc init call for singleton pattern from other classes. I had tested this code with xCode 7.0+ and its working fine.

提交回复
热议问题