objective-c - 在 Objective-c 中的单例类上设置初始化可配置变量的好方法是什么?

标签 objective-c singleton

通常我曾经按照以下方法构建单例:

+ (MyClass *)sharedInstance 
{       
    static MyClass *_sharedInstance = nil;
    static dispatch_once_t oncePredicate;

    dispatch_once(&oncePredicate, ^{
        _sharedInstance = [[self alloc] init];
        // Init variables
    });

    return _sharedInstance;
}

然后我可以调用如下方法:

[[MyClass sharedInstance] anyInstanceMethod];

但是,当任何初始化变量都是类外部的可配置变量时会发生什么? 我的方法是创建两个类方法,其中一个带有可配置变量:

+ (MyClass *)sharedInstanceWithVariableOne:(NSString*)aParamOne andVariableTwo:(NSString*)aParamTwo 
{       
    static MyClass *_sharedInstance = nil;
    static dispatch_once_t oncePredicate;

    dispatch_once(&oncePredicate, ^{
        _sharedInstance = [[self alloc] init];

        // Init configurables variables
        _sharedInstance.paramOne = aParamOne;
        _sharedInstance.paramTwo = aParamTwo;
    });

    return _sharedInstance;
}

第二个作为最后一个具有默认值的代理:

   + (MyClass *)sharedInstance
    {       
        return [MyClass sharedInstanceWithVariableOne:@"value1" andVariableTwo:@"value2"];
    }

因此,如果您想使用带有配置变量的单例类,您应该首先调用 sharedInstanceWithVariableOne:andVariableTwo,然后才调用 sharedInstance。 我认为这种方法不是最好的,我期待使用其他方法。

提前致谢。

最佳答案

感谢您的快速回复。 正如你所说,它不是单例。 我将使用与 [NSURLCache setSharedURLCache:][NSURLCache sharedURLCache] 相同的行为。

界面

// MyClass.h
@interface MyClass : NSObject

+ (MyClass *)sharedMyClass;
+ (void)setSharedMyClass:(MyClass *)object;

- (id)initWithParamOne:(NSString)p1 andParamTwo:(NSString)p2;
@end

实现

// MyClass.m
@interface MyClass ()
@property(nonatomic, strong) NSString *paramOne;
@property(nonatomic, strong) NSString *paramTwo;
@end;

@implementation MyClass

static MyClass *_sharedInstance = nil;

+ (MyClass *)sharedMyClass
{
    if (_sharedInstance == nil) {
        _sharedInstance = [[MyClass alloc] initWithParamOne:@"value1" andParamTwo:@"value2"];
    }

    return _sharedInstance ;
}

+ (void)setSharedMyClass:(MyClass *)object
{
    _sharedInstance = object;
}

- (id)initWithParamOne:(NSString)p1 andParamTwo:(NSString)p2
{
    self = [super init];
    if (self) {
        _paramOne = p1;
        _paramTwo = p2;
    }

    return self;
}

然后我可以使用[[MyClass sharedMyClass] anyMethod]

关于objective-c - 在 Objective-c 中的单例类上设置初始化可配置变量的好方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16021862/

相关文章:

Java 单例模式 - 更新实例化变量

ruby - 什么时候在 Ruby 中分配单例类?

iphone - 您可以将 UITableViewController TableView 添加到另一个 View 吗?

ios - 绘制矩形 :withAttributes dies with "message sent to deallocated instance"

java - 从域对象中访问 Spring 单例的好方法?

java - 正确的单例设计?

java - 使用 Enum 的单例与使用双重检查锁定的单例

ios - NSArray objectAtIndex 索引 0 超出空数组的范围

iphone - 在使用Mapkit时,我可以看到完全可滚动的 map ,但没有看到Apple总部?

ios - UIAlertController 给出错误