Question

I read about singleton on this page does something need to hold a reference to a singleton objective-c object in order to preserve it through the life of an IOS app? and found out that singleton keeps a pointer to itself and therefore need no reference to hold it and keep it alive.

However what if I have a custom class which is a subclass of NSObject and I wrote a code to instantiate a singleton object like this

+ (instancetype)sharedStore{

static CYCImageStore *sharedImageStore = nil;

static dispatch_once_t imageLocation;

dispatch_once(&imageLocation, ^{sharedImageStore = [[self alloc]initPriv];});

return sharedImageStore;
}

Do I need a pointer to it to keep it alive? or is it that it share the same characteristic of other singleton like UIApplication class and more.

Was it helpful?

Solution

You need nothing just use it

[[SingletonClass sharedStore] CYCImageStore];

SingletonClass is the name of your singleton class.

In the same way you can create any method you want and call it.

OTHER TIPS

A singleton class returns the same instance no matter how many times an application requests it. A typical class permits callers to create as many instances of the class as they want, whereas with a singleton class, there can be only one instance of the class per process. A singleton object provides a global point of access to the resources of its class. Singletons are used in situations where this single point of control is desirable, such as with classes that offer some general service or resource.

In your code,

dispatch_once(&imageLocation, ^{sharedImageStore = [[self alloc]initPriv];});

this section will only executes once. So the initialization only takes place once. Since from the second time it will skip the initialization section. So the data once stored will not be reset because of initialization. You dont need to do any additional work or bother about initialization. Access the methods by using your sharedStore method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top