Note that there are some explanatory texts on larger screens.

plurals
  1. POshort call for singleton
    primarykey
    data
    text
    <p><strong>Update with working code. Problem was like @HotLinks state, that I did <code>init</code> instead of <code>initWithBaseURL:url</code></strong></p> <p>I am using a <code>Singleton</code> in my App, based on <a href="http://www.johnwordsworth.com/2010/04/iphone-code-snippet-the-singleton-pattern/" rel="nofollow">this guide</a>. </p> <p>Now every time I use the singleton I do like this: </p> <pre><code>SingletonClass* sharedSingleton = [SingletonClass sharedInstance]; [sharedSingleton callAMethod]; // or [[SingletonClass sharedInstance] callAMethod]; </code></pre> <p><strong>Is there a way to use a short syntax, especially if I have to use the <code>Singleton</code> several times?</strong> Something like: </p> <pre><code>[sc callAMethod]; </code></pre> <p>I tried already this kind, but it did not work, as the init method was not called... </p> <h3>WebApi.h</h3> <pre class="lang-c prettyprint-override"><code>#import "AFHTTPRequestOperationManager.h" #import "SingletonClass.h" @interface WebApi : AFHTTPRequestOperationManager @property (nonatomic, strong) SingletonClass *sc; +(WebApi*)sharedInstance; -(void)sandbox; @end </code></pre> <h3>WebApi.m (updated with working code)</h3> <pre class="lang-c prettyprint-override"><code>#import "WebApi.h" @implementation WebApi //-(WebApi*)init { -(WebApi*)initWithBaseURL:url { self = [super init]; if (self != nil) { self.sc = [SingletonClass sharedInstance]; // is never called. } return self; } #pragma mark - Singleton methods /** * Singleton methods */ +(WebApi*)sharedInstance { static WebApi *sharedInstance = nil; static dispatch_once_t oncePredicate; dispatch_once(&amp;oncePredicate, ^{ sharedInstance = [[self alloc] initWithBaseURL:[NSURL URLWithString:kApiHost]]; }); return sharedInstance; } -(void)sandbox { DLog(@"test short singleton call: %@", [sc callAMethod]; } @end </code></pre> <h3>Debug Message</h3> <blockquote> <p>[WebApi sandbox] [Line 42] test short singleton call: (null)</p> </blockquote>
    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.
 

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