View Single Post
  #2 (permalink)  
Old June 9th, 2012, 02:18 PM
thepianoguy thepianoguy is offline
Friend of Wrox
Points: 1,671, Level: 16
Points: 1,671, Level: 16 Points: 1,671, Level: 16 Points: 1,671, Level: 16
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
Join Date: Aug 2010
Posts: 298
Thanks: 1
Thanked 62 Times in 60 Posts

Proper memory management is best handled by using accessors.The pattern used in the project is useful in helping the programmer avoid unintentional direct setting of instance variables. It also also prevents data hiding when local variables have the same name as instance variables.

From the example in the book the header file
#import <UIKit/UIKit.h>

@class HelloWorldViewController;

@interface EmptyAppAppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

@property (strong, nonatomic) HelloWorldViewController *viewController;    

could have had in the .m file the following
@synthesize window;

@synthesize viewController;
This would have allowed both of the following

viewController = [[[HelloWorldViewController alloc] initWithNibName:@"HelloWorldViewController" bundle:nil] autorelease];

self.viewController = [[[HelloWorldViewController alloc] initWithNibName:@"HelloWorldViewController" bundle:nil] autorelease];
These are not the same.
The first one sets the variable directly and the second uses the accessor. The first version has an object ownership problem, since the object will be deallocated when autorelease is called and viewController will probably end up pointing to garbage. The second one would have a synthesized setter similar to the following:

-(void)setViewController:(HelloWorldViewController *)aViewController
    [aViewController retain];
    [viewController release];
    viewController = aViewController;
Where the variable in is retained to balance the autorelease. The old viewController is released so that it is deallocated unless retained by another object somewhere else, and the viewController stores the pointer to variable in.
The @synthesize variable = _variable; pattern will result in a compiler error if an attempt to directly set the variable e.g.
variable = newVariable;
is attempted.
On the rare occasion where the variable does need to be acted on directly you call the variable with the underscore
_variable = newVariable;
Reply With Quote