I have a question regarding the safe way of implementing a singleton class in Objective-C. My background is mostly in web-development (PHP) but I know that in Obj-C things are quite different. For instance I have this custom class MyClass that I want to be singleton:
static MyClass *sharedInstance = nil;
@interface MyClass:NSObject
NSMutableArray *someArray;
@end
@implementation MyClass:NSObject
-(id)init
{
if(sharedInstance) {
self = sharedInstance;
} else if((self=[super init])) {
sharedInstance = self;
someArray = [[NSMutableArray alloc]initWithCapacity:10];
}
return self;
}
+(MyClass *)sharedObject
{
if(!sharedInstance) {
sharedInstance = [[MyClass alloc]init];
}
return sharedInstance;
}
@end
- It's ok this implementation?
- Since in Obj-C I can't make the constructor private (as far as I know, maybe I'm wrong), it's ok this way of creating the init method?