6

在您看来,如果我有一个 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?
}

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

4

1 回答 1

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;
}
于 2012-06-01T11:57:49.200 回答