iOS:按需引用单例还是保留它更好?
在我的 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为什么将引用存储在应用程序委托中,而不是存储在单例对象本身的静态变量中 - 这是常见的做法?
如果你因为在单例 init 中初始化了很多对象而担心性能问题,那么只需在需要数据时进行延迟初始化即可。
在应用程序委托中存储对象并不是真正的单例。您可以使用 GCD 创建一个像这样的单例。
在每个视图控制器中创建许多不必要的访问器纯粹是过度杀伤和浪费时间。
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.
Creating many unnecessary accessors in each view controller is just pure overkill and a waste of time.