This is not the usual way to implement singleton, and you are breaking the init
convention. It would be better to create a method of the sharedInstance
class and leave the initWithParam
more ordinary:
static MyObject *_sharedInstance = nil; + (MyObject *)sharedInstance:(NSString *)param { if (_sharedInstance == nil) { _sharedInstance = [MyObject alloc] initWithParam:param]; } return _sharedInstance; }
However, even this is not very convenient; that is, what happens if the user calls sharedInstance
with a different parameter? Perhaps you want to keep NSMutableDictionary
initialized objects and create / restore them depending on the parameter?
If so, you would do:
static NSMutableDictionary _sharedInstances = [[NSMutableDictionary alloc] init]; + (MyObject *)sharedInstance:(NSString *)param { MyObject *obj = [_sharedInstances objectForKey:param]; if (obj == nil) { obj = [[MyObject alloc] initWithParam:param]; [_sharedInstances setObject:obj forKey:param]; } return obj; }
source share