Search code examples
objective-ccocoamemory-managementsingletonretain

What is the point of retaining a singleton you've accessed?


Is there any point to using retain on a singleton? I believe the whole point of using the singleton pattern is to keep one global object to access from various classes. What would be a case to use retain on such an object?

Generally, the implementation of retain in a singleton class returns self (not singleton instance) like below:

-(id)retain
{
   return self;
}

I recently went through some open source code, and the author repeatedly retained the singleton

object = [[SingletonClass shareObject] retain]

and released it in dealloc.

So when I tried to build this project, it worked at first, then crashed when it attempted to access variables on singleton object later.

What would happen exactly, if I retain a singleton object and attempt to access it?


Solution

  • Just because it's a singleton doesn't mean its lifetime is necessarily the lifetime of the process. For example, you might have some singleton that obtains a resource. But until you need that resource, there's no point in creating it. Likewise, you might know that all instances are done with that resource, so why keep it around? An easy way to keep track of whether a singleton needs to continue to exist is its retain count.

    For example, you might have a singleton that represents the video camera built-in to a user's device. There might be different parts of your application that need to access the camera. But it might also be possible to use your app without the camera, or the workflow may dictate that the camera is turned off at some point (for privacy, or whatever). So you don't allocate the singleton until the user initiates an action that starts camera use. They may do several actions with the camera, such as take a picture, scan a QR code, record some video, etc. Then they may end all of those actions and need the memory taken by the camera freed up (especially on a mobile device). So they end those actions. If each camera-related actions retained the camera singleton, then each released it when they were done, you could free up the memory and other resources used by the camera, even though it's still a singleton.