I know Singleton class is a class whose only one object can be created at a time.
My questions are:
1.What is the use of Singleton class in objective-c?
2.How to create and use the created Singleton class?
I know Singleton class is a class whose only one object can be created at a time.
My questions are:
1.What is the use of Singleton class in objective-c?
2.How to create and use the created Singleton class?
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() { }
}