Interface Builder中的Singleton与ARC [英] Singleton in Interface Builder with ARC

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

问题描述

我的问题与此非常相似:在Interface Builder中使用Singleton?

My question is quite similar to this one: Use Singleton In Interface Builder?

唯一的区别是我使用ARC。所以,如果简化,我的单身看起来像这样:

The only difference is that I use ARC. So, if simplified, my singleton looks like that:

Manager.m

@implementation Manager

+ (instancetype)sharedManager {
    __strong static id sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
    });
    return sharedInstance;
}

@end

所以问题是它是否是是否可以将它用于仍然使用ARC的Interface Builder?

So the question is if it's possible to adopt it for Interface Builder still being with ARC?

当然,我理解在没有ARC的情况下重写该类可能更简单所以问题是相当学术性的。 :)

Of course, I understand that it might be simpler just to rewrite that class without ARC so the question is rather academic. :)

推荐答案

当nib被取消存档时,它将尝试 alloc / init alloc / initWithCoder: a该类的新实例。

When the nib is unarchived, it'll attempt to either alloc/init or alloc/initWithCoder: a new instance of the class.

所以,你可以做的就是拦截那个电话并重新路由它以返回你的单身:

So, what you could do is intercept that call and re-route it to return your singleton:

+ (id)sharedInstance {
  static Singleton *sharedInstance = nil;
  static dispatch_once_t onceToken;
  dispatch_once(&onceToken, ^{
    sharedInstance = [[self actualAlloc] actualInit];
  });
  return sharedInstance;
}

+ (id)actualAlloc {
  return [super alloc];
}

+ (id)alloc {
  return [Singleton sharedInstance];
}

- (id)actualInit {
  self = [super init];
  if (self) {
    // singleton setup...
  }
  return self;
}

- (id)init {
  return self;
}

- (id)initWithCoder:(NSCoder *)decoder {
  return self;
}

这允许 -init -initWithCoder:可以在同一个对象上安全地多次调用。通常不建议允许这样做,但鉴于单身人士已经处于事情变得非常糟糕的地方,这不是你能做的最糟糕的事情。

This allows -init and -initWithCoder: to be safely called multiple times on the same object. It's generally not recommended to allow this, but given that singletons are already cases of "a place where things can get really wonky", this isn't the worst you could do.

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

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