ios - Objective-C 单例 GCD - [self alloc] 或 [Class alloc]
<p><p>在引入 <code>instance</code> 后,我正在研究现代的 Objective-C 模式来创建单例 </p>
<p>来自:<a href="https://stackoverflow.com/questions/5720029/create-singleton-using-gcds-dispatch-once-in-objective-c" rel="noreferrer noopener nofollow">Create singleton using GCD's dispatch_once in Objective C</a> </p>
<pre><code>+ (instancetype)sharedInstance
{
static dispatch_once_t once;
static id sharedInstance;
dispatch_once(&once, ^
{
sharedInstance = ;
});
return sharedInstance;
}
</code></pre>
<p>我想知道为什么不使用下面的 ?</p>
<pre><code>@implementation MyFunnyClass
+ (instancetype)sharedInstance
{
static dispatch_once_t once;
static id sharedInstance;
dispatch_once(&once, ^
{
sharedInstance = ;
});
return sharedInstance;
}
</code></pre>
<p>或者如果它是一样的?</p>
<p>(引用:<a href="http://nshipster.com/instancetype/" rel="noreferrer noopener nofollow">http://nshipster.com/instancetype/</a>)</p>
<p>编辑:<a href="https://stackoverflow.com/questions/3559763/why-use-classname-alloc-instead-of-self-class-alloc" rel="noreferrer noopener nofollow">Why use instead of [ alloc]?</a> 给出的答案与本题无关</p></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>在这种情况下,使用 <code></code> 而不是 <code></code> 并使用 <code>static id sharedInstance</code> 的原因而不是 <code>static MyClass *sharedInstance</code>,是因为您可以复制和粘贴整个方法而无需对其进行编辑。该方法中没有任何内容特定于它所属的类。</p></p>
<p style="font-size: 20px;">关于ios - Objective-C 单例 GCD - 或 ,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/32851847/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/32851847/
</a>
</p>
页:
[1]