This is how I usually use the singleton method
+(SampleSingleton * )sampleSingleton { static SampleSingleton * theSampleSingleton = nil; if( theSampleSingleton == nil ) theSampleSingleton = [[SampleSingleton alloc] init]; return theSampleSingleton; }
to make this thread safe you would do
+(SampleSingleton * )sampleSingleton { static SampleSingleton * theSampleSingleton = nil; if( theSampleSingleton == nil ) { @syncronise([SampleSingleton class]) { if( theSampleSingleton == nil ) theSampleSingleton = [[SampleSingleton alloc] init]; } } return theSampleSingleton; }
In addition, instead of using singleton, you already have a singleton in the form of UIApplicationDelegate, you can always add a delegation method to get your SampleSingleton from your delegate.
Another point to consider about singletones is that you really need to enforce singletones, UIApplication has a sharedApplication that has the function of creating a singleton, but there is nothing really stopping you from creating a new instance.
Nathan day
source share