iOS:按需引用单例还是保留它更好?

发布于 2024-12-09 17:46:59 字数 259 浏览 1 评论 0原文

在我的 iOS 应用程序中,我有一组单例对象,这些对象是在应用程序启动时由我的应用程序委托创建的,并且可以从应用程序的每个视图控制器访问它们。这些对象存储为应用程序委托属性。

我想知道每次需要时获取对这些对象的引用([SharedAppDelegate.singletonName 方法])是否是更好的做法,或者为每个需要该对象的视图控制器存储私有引用是否更好?

也许需要根据我访问该对象的次数进行权衡?还是我想太多了,实际上没有什么区别?

预先非常感谢。

In my iOS application I have a set of singleton objects which are created by my app delegate when the application starts, and they are meant to be reachable from every view controller of the application. These objects are stored as app delegate properties.

I would like to know if it is a better practice to get the reference to these objects everytime I need it ([SharedAppDelegate.singletonName method]) it or is it better to store a private reference for each view controller who will need the object?

Maybe there's a tradeoff based on how many times I will access that object? Or I'm just overthinking and there's practically no difference?

Thanks so much in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦里梦着梦中梦 2024-12-16 17:46:59

为什么将引用存储在应用程序委托中,而不是存储在单例对象本身的静态变量中 - 这是常见的做法?

如果你因为在单例 init 中初始化了很多对象而担心性能问题,那么只需在需要数据时进行延迟初始化即可。

在应用程序委托中存储对象并不是真正的单例。您可以使用 GCD 创建一个像这样的单例。

@interface MYSingleton

+ (id)sharedInstance;

@end

@implementation MYSingleton

+ (id)sharedInstance {
  static dispatch_once_t once;
  static MyFoo *sharedInstance;
  dispatch_once(&once, ^{
    sharedInstance = [[self alloc] init];
  });
  return sharedInstance;
}

@end

在每个视图控制器中创建许多不必要的访问器纯粹是过度杀伤和浪费时间。

Why store a reference in the app delegate and not in a static var in the singleton object itself - as it is common practice?

If you are concerned about performance problems because you initialize many objects in the singletons init, just do lazy initialization when the data is needed.

Storing an object in the app delegate is no real singleton. You can create a singleton for instance like this using GCD.

@interface MYSingleton

+ (id)sharedInstance;

@end

@implementation MYSingleton

+ (id)sharedInstance {
  static dispatch_once_t once;
  static MyFoo *sharedInstance;
  dispatch_once(&once, ^{
    sharedInstance = [[self alloc] init];
  });
  return sharedInstance;
}

@end

Creating many unnecessary accessors in each view controller is just pure overkill and a waste of time.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文