Objective-C: Where is My Object Retained?

Apologies for the gap since my last post. Its been a long week as my wife and I were in a serious car accident a week ago today. Ill spare the details, however, let it suffice to say that our vacation plans didnt include all the drama that unfolded that day. We are both on the mend and have plans for a full recovery. Lets get back into it

For those new to Objective-C and iPhone development, I want to point out something that might save you some time. Look at the code below:

@interface SomeClass : UIViewController

	UIView *containerView;
@implementation SomeClass
- voidloadView

  UIView *uiView = UIView alloc initWithFrame:
     UIScreen mainScreen applicationFrame;
  self.containerView = uiView;
  uiView release;


In this block of code, I am setting up a container view, that will hold several subviews. Once the assignment is complete on line 8, I release the local object uiView. Question is, how I can I get away with releasing the variable and still have access to the view in the SomeClass object? In other words, where is the retain?

First thing to notice is that the dot syntax is shorthand for accessing class instance variables using Objective-C properties. If one were to write the code without using properties (and thus, no dot syntax) the answer is obvious.

For example, the equivalent code directly calling the accessor (setter) method would look as follows:

self setContainerView:uiView;
uiView release;

At this point, if one was curious about where the object was retained (before the release), the obvious place to look is inside the setter, which might look as follows:

- void setContainerView:UIView * view

  view retain;
  containerView release;
  containerView = view;

Easy enough, the object is retained as part of the setter. What we have here is a good example of pros/cons when working with properties. On one hand, properties allow for simplification and consistency in our code. On the other hand, if using properties and we request the compiler to implement the getter/setter methods (through use of the @synthesize directive) there is code created for us to implement these methods, which we never see.

Although properties are no doubt handy, as this example illustrates, its important to understand what is happening behind the scenes. A clear picture of the little nuances can go a long ways when it comes to debugging a thorny problem.

Leave a Reply

Your email address will not be published. Required fields are marked *