类方法中的IOS内存泄漏

时间:2012-06-01 11:49:13

标签: iphone objective-c ios

在您看来,如果我使用这样的参数初始化NSObject的单例子类:

- (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?
}

用户无权访问实例方法,只能访问类。感谢。

1 个答案:

答案 0 :(得分:3)

这不是实现单例的正常方式,而是打破了init的约定。更好的方法是创建一个sharedInstance类方法,让initWithParam方法更加传统:

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;
}

然而,即使这样看起来也不太舒服;即,如果用户使用不同的参数调用sharedInstance会发生什么?也许您想保留NSMutableDictionary初始化对象并根据参数创建/返回它们?

如果是这样,你会这样做:

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;
}