IOS memory leak in class method

In your opinion, if I have a singleton subclass of NSObject that is initialized with parameters such as:

- (MyObject *) initWithSomeParam:(NSString *)param{ self = [super init]; if (SharedInstance == nil){ SharedInstance = [super init]; SharedInstance.someProperty = param; } return self; } + (MyObject *) objectWithSomeParam:(NSString *)param{ return [[self alloc] initWithSomeParam:param]; // Will the alloc cause a leak? } 

The user does not have access to the instance method, just a class. Thanks.

+6
source share
1 answer

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; } // This must be called during app termination to avoid memory leak + (void)cleanup { [_sharedInstance release]; _sharedInstance = nil; } - (id)initWithParam:(NSString *)param { self = [super init]; if (self != nil) { self.someProperty = param; } return self; } 

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; } // This must be called during app termination to avoid memory leak + (void)cleanup { [_sharedInstances release]; _sharedInstances = nil; } 
+3
source

Source: https://habr.com/ru/post/917175/


All Articles