Correct way to host a shared instance (singleton)?

I look at the singleton, and I was curious how to distribute, looking at documents, books and web pages, it seems, several methods.

M1:

static ReactorClass *sharedReactor = nil;
+(ReactorClass *)sharedInstance {
    if(sharedReactor == nil) {
        sharedReactor == [[ReactorClass alloc] init];
    }
    return sharedReactor;
}

M2:

static ReactorClass *sharedReactor = nil;
+(ReactorClass *)sharedInstance {
    if(sharedReactor == nil) {
        sharedReactor == [[super allocWithZone:NULL] init];
    }
    return sharedReactor;
}

M3:

static ReactorClass *sharedReactor = nil;
+(ReactorClass *)sharedInstance {
    if(sharedReactor == nil) {
        sharedReactor == [[[self class] alloc] init];
    }
    return sharedReactor;
}

many thanks...

Gary

+3
source share
3 answers

Using [self class] is really a waste in this case - M1 and M3 are not really different from each other unless you have subclasses, and the reality is that the rest of the implementation cannot handle it.

Consider what happens if you subclass ReactorClass as follows:

@interface MyReactorClass : ReactorClass {}
@end
@implementation MyReactorClass
@end

[MyReactorClass sharedInstance], , sharedReactor. , , , , , , , . , , M3 , , : " ?" - , , , .

, ( + ) , .

, alloc allocWithZone: , , , , , , . singleton, DOCUMENT, , , , .

, init, (ok, _init) - , , singleton, .

, " ". , , , , .. , , , . Apple ; , .

+2

:

+ (id)sharedFoo
{
    static Foo *_sharedFoo;

    if (_sharedFoo == nil)
    {
        _sharedFoo = [[self alloc] init];
    }

    return _sharedFoo;
}

, . , , +initialize.

+3

If you put M3 in a ReactorClass implementation, then this is the same as M1, allocating and returning a ReactorClass. However, if M3 can be added to the implementation of the ReactorClass subclass, it will return a pointer to the object of this subclass.

M2 always returns the superclass of the implementation it is in.

+1
source

Source: https://habr.com/ru/post/1736124/


All Articles