我知道 Singleton 类是一个类,它一次只能创建一个对象。
我的问题是:
1 、objective-c中Singleton类有什么用?
2 、如何创建和使用创建的Singleton类?
我知道 Singleton 类是一个类,它一次只能创建一个对象。
我的问题是:
1 、objective-c中Singleton类有什么用?
2 、如何创建和使用创建的Singleton类?
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() { }
}
单例是一种特殊的类,其中当前进程只存在该类的一个实例。对于 iPhone 应用程序,一个实例在整个应用程序中共享。
看看这些教程:
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.galloway.me.uk/tutorials/singleton-classes/
这是另一个:如何在目标 C 中创建单例类
单例包含全局变量和全局函数。它是在代码的不同部分之间共享数据的一种非常强大的方式,而无需手动传递数据。