Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat is a good approach to set init configurables variables on singleton classes in Objective-c?
    primarykey
    data
    text
    <p>Nomaly I used to build a singleton the following recipe:</p> <pre><code>+ (MyClass *)sharedInstance { static MyClass *_sharedInstance = nil; static dispatch_once_t oncePredicate; dispatch_once(&amp;oncePredicate, ^{ _sharedInstance = [[self alloc] init]; // Init variables }); return _sharedInstance; } </code></pre> <p>Then I can call methods as following:</p> <pre><code>[[MyClass sharedInstance] anyInstanceMethod]; </code></pre> <p>But, what happen when any init variables are configurables from outside the class? My approach is create two class methods, one of them with configurables variables:</p> <pre><code>+ (MyClass *)sharedInstanceWithVariableOne:(NSString*)aParamOne andVariableTwo:(NSString*)aParamTwo { static MyClass *_sharedInstance = nil; static dispatch_once_t oncePredicate; dispatch_once(&amp;oncePredicate, ^{ _sharedInstance = [[self alloc] init]; // Init configurables variables _sharedInstance.paramOne = aParamOne; _sharedInstance.paramTwo = aParamTwo; }); return _sharedInstance; } </code></pre> <p>And the second one as proxy to this last one with default values:</p> <pre><code> + (MyClass *)sharedInstance { return [MyClass sharedInstanceWithVariableOne:@"value1" andVariableTwo:@"value2"]; } </code></pre> <p>So, if you want to use singleton class with configure variables, you should call first of all <code>sharedInstanceWithVariableOne:andVariableTwo</code> and then only <code>sharedInstance</code>. I think this approach is not the best and I'm looking forward to use others.</p> <p>Thanks in advance.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload