-1

I have created a single ton like this for ARC,

+ (MyClass *)sharedInstance {
    static MyClass *sharedSpeaker = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedSpeaker = [[self alloc] init];
    });
    return sharedSpeaker;
}

- (id)init {
    if (self = [super init]) {

    }
    return self;
}

But here I am creating instances like this:

id speaker3 = [[MyClass alloc] init];
id speaker = [MyClass sharedInstance];
id speaker2 = [[MyClass alloc] init];
NSLog(@"Speaker 1= %@ \n speaker 2 = %@\n Speaker3 = %@",speaker,speaker2,speaker3);`

I got output as:

Speaker 1= <MyClass : 0xa45f5e0> 
speaker 2 = <MyClass : 0xa461740>
Speaker3 = <MyClass : 0xa4529e0>

This is looking like a desired behaviour. How to stop this when I am giving singleton in library to user. I need to block him from creating new instance. Do I need to make static global if I make it global he cant create the global variable of the same name there will be conflict right. So any memebers can give solution on this?

4

4 回答 4

3

例如在init方法中使用断言。

- (id)init {
    static int maxInstances = 1;

    assert(maxInstances > 0);

    maxInstances--;

    ...
}
于 2013-04-01T12:34:36.913 回答
0

因为您正在使用alloc,创建单例类的新实例init

您将使用sharedInstance类方法获得单例实例。喜欢:

id speaker = [MyClass sharedInstance];

如果您不想使用alloc或创建实例init。覆盖这些方法。

您可以编写static MyClass *sharedSpeaker = nil;为静态全局变量并将其从sharedInstance方法中删除。

于 2013-04-01T12:31:27.680 回答
0
create instance like this it will always return you singlton

static testSinglton *myinstance = nil;
+ (testSinglton *) sharedInstance {
    if (!myinstance) {
        myinstance = [[testSinglton alloc] init];
    }
    return myinstance;
}

- (id) init {

    if (myinstance) {
        return myinstance;
    }
    if (self = [super init]) {
        //new object now will be created...
        myinstance = self;
    }
    return self;
}

 NSLog(@"%@",[[testSinglton alloc] init]);
 NSLog(@"%@",[testSinglton sharedInstance]);
 NSLog(@"%@",[[testSinglton alloc] init]);
于 2013-04-01T14:15:47.597 回答
0

在 .h 文件中

    #import <Foundation/Foundation.h>

    @interface Singleton : NSObject 
    {
            ///......
    }

    + (Singleton *)sharedSingleton;

在 .m 文件中

    #import "Singleton.h"

    @implementation Singleton
    static Singleton *singletonObj = NULL;

    + (Singleton *)sharedSingleton 
    {
            @synchronized(self) 
            {
                    if (singletonObj == NULL)
                            singletonObj = [[self alloc] init];
            }
            return(singletonObj);
    }

并在另一个文件中使用它

    #import "Singleton.h"
    //.....

    Singleton *sinObj =  [Singleton sharedSingleton];   // not alloc and init. use direct
于 2013-04-01T12:56:08.147 回答