-1

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?

Rui Peres
  • 25,741
  • 9
  • 87
  • 137
liza
  • 3,687
  • 3
  • 16
  • 18
  • 1.) the same as in any other language 2.) http://stackoverflow.com/questions/5381085/how-to-create-singleton-class-in-objective-c?lq=1 – peko Apr 25 '13 at 08:16
  • Singleton Class have only single instance in a memory at time so what ever object we crated and destroy it but normal class declaration we crated many objects so some times you don't destroy it right time so it will produce memory leaks. – annu May 31 '17 at 14:26

1 Answers1

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() { }
}
Rui Peres
  • 25,741
  • 9
  • 87
  • 137
  • Singleton Class have only single instance in a memory at time so what ever object we crated and destroy it but normal class declaration we crated many objects so some times you don't destroy it right time so it will produce memory leaks. – annu May 31 '17 at 14:26