Apologies for the gap since my last post. It’s been a long week as my wife and I were in a serious car accident a week ago today. I’ll spare the details, however, let it suffice to say that our vacation plans didn’t include all the drama that unfolded that day. We are both on the mend and have plans for a full recovery. Let’s 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 *uiView = [[UIView alloc] initWithFrame:
[[UIScreen mainScreen] applicationFrame]];
self.containerView = uiView;
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:
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
containerView = view;
Easy enough, the object is retained as part of the setter. What we have here is a good example of pro’s/con’s 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, it’s 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.