ios singleton class crashes my app

后端 未结 3 1154
一整个雨季
一整个雨季 2021-01-26 06:18

I have a problem with an singleton pattern.

I have read the following tutorials about singleton classes and have created my own. http://www.galloway.me.uk/utorials/sing

3条回答
  •  不要未来只要你来
    2021-01-26 06:50

    The solution of Jano must work well. I use this way too to create singleton object. And I don't have any problem.

    For your code, I think that if you use @synchronized (it's not necessary cause your have dispatch_once_t as Jano said), you should not call return in @synchronized.

    + (BPManager *) bpManager {
        @synchronized(self) {
            if(sharedMyManager == nil) {
                static dispatch_once_t pred;        // Lock
                dispatch_once(&pred, ^{             // This code is called at most once per app
                    sharedMyManager = [[BPManager alloc] init];
                });
            } 
        }
    
        return sharedMyManager;
    }
    

提交回复
热议问题