p2p.wrox.com Forums

p2p.wrox.com Forums (http://p2p.wrox.com/index.php)
-   BOOK: Beginning iOS 5 Application Development (http://p2p.wrox.com/forumdisplay.php?f=670)
-   -   Empty Application Chapter4 Page 81 (http://p2p.wrox.com/showthread.php?t=87701)

jtown June 7th, 2012 10:09 AM

Empty Application Chapter4 Page 81
 
Code:

@synthesize window = _window;
@synthesize viewController = _viewController;

I understand that we are initializing accessor methods for window and viewController but whats the _windows & _viewController?

thepianoguy June 9th, 2012 02:18 PM

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
Code:

#import <UIKit/UIKit.h>

@class HelloWorldViewController;

@interface EmptyAppAppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

@property (strong, nonatomic) HelloWorldViewController *viewController;   

@end

could have had in the .m file the following
Code:

@synthesize window;

@synthesize viewController;

This would have allowed both of the following

Code:

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

Code:

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:

Code:

-(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.
Code:

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
Code:

_variable = newVariable;
Bob


All times are GMT -4. The time now is 10:49 AM.

Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
© 2013 John Wiley & Sons, Inc.