开发者

iOS: is it better to get reference to a singleton on demand or to keep it?

开发者 https://www.devze.com 2023-04-12 17:33 出处:网络
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 applicati

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 obj开发者_如何学Pythonects 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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消