tags:

views:

257

answers:

3

If we write the following code:

ExplorerAppDelegate * appDelegate = (ExplorerAppDelegate *)[[UIApplication sharedApplication] delegate];

This makes a reference to the original delegate pointer, but:

  • Does it increase the reference count?
  • Do we have to explicitly call as [ExplorerAppDelegate retain] right after, or not at all?
  • What's happening, exactly?

After we've used this, we should also do a [ExplorerAppDelegate release] in the dealloc method, right?

A: 
  1. The reference count will not be increased
  2. You should retain it if you want to be sure that it isn't deallocated while you have a pointer to it
  3. You should only release it if you retained it

So basically, if you're only using the object in a single function, you probably don't need retain or release it. If it exists when you get it, then it's (probably) not going to be deallocated by the end of the function. If you're keeping it around, in an ivar (member variable) for example, then you should retain it and release it later.

Tom Dalling
Thank you for your answer..:)
This is all valid, and perfectly correct. But ... since the application delegate is created at application launch, and is never released (at least not until termination), you can simple keep the reference, not retain it, and ignore the issue entirely. In this case, you know the reference will remain valid for the lifetime of the application.
Peter N Lewis
+2  A: 

No, it does not increase the retain count.

The convention in Objective-C is that objects you are given should be memory managed by yourself - but in the case of obtaining a shared common resource like the app delegate, the memory is maintained elsewhere and of course (with this being the app delegate) you know that it will always be "alive" as long as your class is... so there is no need to retain the reference.

In most uses of delegates, instead of fetching a delegate you are given one, and that reference is not retained either. In that case whoever gave you the delegate is also responsive for clearing out the delegate link before the delegate is released.

The reason you don't want to generally retain delegate references is that it can prevent some objects from being deallocated, for instance if one class is a delegate of a class that ues the other class as a delegate.

Kendall Helmstetter Gelner
Thank you for your answer..:)
A: 

See the "Weak References to Objects" in Memory Management Programming Guide for Cocoa for the official answer. Pointers to delegates are one of the possible exception cases to the memory management rules.

johne