-1

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

我的问题是:

1 、objective-c中Singleton类有什么用?

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

4

3 回答 3

12

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 UIViewControllers need 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.

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:

class Manager {

    static let sharedManager = Manager()
    private init() { }
}
于 2013-04-25T06:45:57.723 回答
7

单例是一种特殊的类,其中当前进程只存在该类的一个实例。对于 iPhone 应用程序,一个实例在整个应用程序中共享。

看看这些教程:

http://pixeleap.com/?p=19

http://www.codeproject.com/Tips/232321/Implement-Objective-C-Singleton-Pattern

http://xcodenoobies.blogspot.in/2012/08/how-to-pass-data-between.html

http://www.johnwordsworth.com/2010/04/iphone-code-snippet-the-singleton-pattern/

http://www.idev101.com/code/Objective-C/singletons.html

还有这个视频教程:

http://www.youtube.com/watch?v=FTfEN8KQPK8

于 2013-04-25T07:07:40.697 回答
3

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

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

单例包含全局变量和全局函数。它是在代码的不同部分之间共享数据的一种非常强大的方式,而无需手动传递数据。

于 2013-04-25T06:41:30.197 回答