ios Objective-c 中 Singleton 类的用途是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16208041/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 23:20:08  来源:igfitidea点击:

What is the use of Singleton class in objective-c?

iosobjective-csingleton

提问by liza

I know Singleton class is a class whose only one object can be created at a time.

我知道 Singleton 类是一次只能创建一个对象的类。

My questions are:

我的问题是:

1.What isthe use of Singleton class in objective-c?

1.什么是Objective-C中使用Singleton类的?

2.How tocreate and use the created Singleton class?

2、如何创建和使用创建的Singleton类?

回答by Rui Peres

You normally use a Singleton when you want to expose something to the entire project, or you want a single point of entry to something. Imagine that you have a photos application, and 3 our 4 UIViewControllersneed to access an Array with Photos. It might(most of the time it doesn't) make sense to have a Singleton to have a reference to those photos.

当您想要向整个项目公开某些内容,或者您​​想要某个内容的单一入口点时,通常会使用 Singleton。想象一下,您有一个照片应用程序,并且 3 我们的 4UIViewControllers需要访问带有照片的数组。让单身人士引用这些照片可能(大多数时候没有)有意义。

A quick implementation can be found here. And would look like this:

可以在此处找到快速实现。看起来像这样:

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

You can see other ways of implementing this pattern here.

您可以在此处查看实现此模式的其他方法。

In Swift 2.1 would look like this:

在 Swift 2.1 中看起来像这样:

class Manager {

    static let sharedManager = Manager()
    private init() { }
}

回答by Vineet Singh

回答by lakesh

Here is an example and tutorial: http://www.galloway.me.uk/tutorials/singleton-classes/

这是一个示例和教程:http: //www.galloway.me.uk/tutorials/singleton-classes/

Here is another one: How to create singleton class in objective C

这是另一个:如何在目标 C 中创建单例类

Singleton contains global variables and global functions.It's an extremely powerful way to share data between different parts of code without having to pass the data around manually.

Singleton 包含全局变量和全局函数。这是一种在代码的不同部分之间共享数据而无需手动传递数据的极其强大的方式。