iOS 5中的Singleton? [英] Singleton in iOS 5?

查看:114
本文介绍了iOS 5中的Singleton?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我有一个实现以前版本的iOS for singleton如下:

Hi I had an implementation previous versions of iOS for a singleton as follows:

.h文件

@interface CartSingleton : NSObject 
{

}
+(CartSingleton *) getSingleton;

.m文件

@implementation CartSingleton

static CartSingleton *sharedSingleton = nil;

+(CartSingleton *) getSingleton
{
    if (sharedSingleton !=nil)
       {
        NSLog(@"Cart has already been created.....");
        return sharedSingleton;
       }
    @synchronized(self)
   {
    if (sharedSingleton == nil)
       {
        sharedSingleton = [[self alloc]init];
        NSLog(@"Created a new Cart");
       }
   }
    return sharedSingleton;
}
//==============================================================================
+(id)alloc
{
    @synchronized([CartSingleton class])
   {
    NSLog(@"inside alloc");
    NSAssert(sharedSingleton == nil, @"Attempted to allocate a second instance of a singleton.");
    sharedSingleton = [super alloc];
    return sharedSingleton;
   }

    return nil;
}

//==============================================================================
-(id)init
{
    self = [super init];
}

然而,在网络上,我看到有人使用此代码实现了Singleton设计模式:

However on the web I see people have implemented the Singleton design pattern using this code:

+ (id)sharedInstance
{
  static dispatch_once_t pred = 0;
  __strong static id _sharedObject = nil;
  dispatch_once(&pred, ^{
    _sharedObject = [[self alloc] init]; // or some other init method
  });
  return _sharedObject;
}

有经验者可以指导我。
我是一个新手,并且在Singleton的旧iOS实现与新的实现之间彻底混淆了哪一个是正确的?

Could someone who is experience please guide me. Im a newbie and thoroughly confused between the old iOS implementation of the Singleton and the new one and which is the correct one?

非常感谢

推荐答案

严格来说,你必须使用:

Strictly speaking, you must use:

+ (MySingleton*) instance {
     static dispatch_once_t _singletonPredicate;
     static MySingleton *_singleton = nil;

     dispatch_once(&_singletonPredicate, ^{
        _singleton = [[super allocWithZone:nil] init];
     });

     return _singleton;
 }

 + (id) allocWithZone:(NSZone *)zone {
      return [self instance];
 }

现在你保证不能调用alloc / init并创建另一个实例。

Now you guarantee that one cannot call alloc/init and create another instance.

说明:实例方法属于类级别,是获取单例引用的主要访问方法。该方法只使用dispatch_once()内置队列,该队列只执行一次块。运行时如何保证块只执行一次?使用您提供的谓词(类型为dispatch_once_t)。这个低级调用将保证即使有多个线程试图调用它,只有一个成功,其他线程等到第一个完成然后返回。

Explanation: The instance method is at the class level and is your main access method to get a reference to the singleton. The method simply uses the dispatch_once() built-in queue that will only execute a block once. How does the runtime guarantee that the block is only executed once? Using the predicate you supply (of type dispatch_once_t). This low-level call will guarantee that even if there are multiple threads trying to call it, only one succeeds, the others wait until the first one is done and then returns.

我们覆盖allocWithZone的原因是因为alloc调用allocWithZone传递nil作为区域(对于默认区域)。为了防止恶意代码分配和初始化另一个实例,我们覆盖allocWithZone,以便传回的实例是已经初始化的单例。这可以防止创建第二个实例。

The reason we override allocWithZone is because alloc calls allocWithZone passing nil as the zone (for the default zone). To prevent rogue code from allocating and init-ializing another instance we override allocWithZone so that the instance passed back is the already initialized singleton. This prevents one from creating a second instance.

这篇关于iOS 5中的Singleton?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆