Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS: Retaining a shared instance

I am using a shared instance of a singleton class in a function, do I need to do a retain on the object? A few examples I have seen do this: AVAudioSession *session = [[ AVAudioSession sharedInstance] retain]; while a few simply do: AVAudioSession *session = [ AVAudioSession sharedInstance];. I am sure there is a rule somewhere which should tell me what to do but I just don't know it.

like image 518
341008 Avatar asked Dec 13 '22 12:12

341008


2 Answers

Simply treat it as if it were any other object. Sometimes a singleton class will override memory management methods to ensure that it doesn't get deallocated, but there is no way to know whether or not a shared object has this. With shared objects and singletons which don't, if the first gets deallocated a new one will be created as needed. Therefore, if you need to ensure that a pointer is valid in a future method, retain the shared object when you get it. If you don't need to keep it, you don't need to do anything as the sharedInstance method will autorelease it.

like image 150
ughoavgfhw Avatar answered Jan 10 '23 21:01

ughoavgfhw


You're right, there are rules that tell you what to do. They're the same rules you use everywhere else in Cocoa Touch. Clients of a singleton shouldn't care that the object they're using is a singleton, and they definitely shouldn't rely on the singleton's single-ness to avoid the usual memory management conventions.

Yes, if you know that an object is a singleton and you know that it won't be deallocated, retaining it might seem redundant. On the other hand, retaining the singleton when you acquire it and releasing it when you're done better documents the programmer's intent and avoids the need to explain to anyone (including the future you) why it's okay not to retain this particular object. Most importantly, it prevents your code from depending on an implementation detail of some other part of your code.

like image 23
Caleb Avatar answered Jan 10 '23 20:01

Caleb