Bradley Thomas
Bradley Thomas

Reputation: 4097

Are retain cycles okay sometimes?

Say I have an object that should exist as a singleton for the whole life of the app. Is it okay for this object to contain, say, a strong reference to an NSTimer with itself as the timer's target? This will be a retain cycle, but I don't see any downside. When the OS tries to free memory, it doesn't necessary call dealloc anyway.

Upvotes: 2

Views: 83

Answers (2)

Abhi Beckert
Abhi Beckert

Reputation: 33369

There is no retain cycle. The timer releases its target once it has finished firing.

A retain cycle is when two objects retain each other forever. Not when it's temporary.

Upvotes: 0

matt
matt

Reputation: 535316

It sounds fine. You have a singleton object, meaning that once created it will persist for the lifetime of the app. To accompany it, you have a timer that will also persist for the lifetime of the app. So once you have ensured their persistence (i.e. they are both retained), there is no memory to manage. They will both live as long as the app does and in this case that is exactly what you want. The fact that there is a retain cycle in the story (because of NSTimer's peculiarities) is, as your question implies, almost secondary.

Upvotes: 3

Related Questions