
Initialization and Deallocation Methods
49
Component Initialization
A component object’s init method is invoked when the component object is
created. Just how often a particular component object is created depends on
whether the application object is caching pages. For more information, see
“WebObjects Viewed Through Its Classes” (page 63). If page caching is
turned on (as it is by default), the application object generally creates the
component object once and then restores that object from the cache every
time it is involved in a user request. If page caching is turned off, the
component object is freed at the end of the request-response loop.
Note: The pageWithName: method shown in the section “Action Methods”
(page 43) always creates a new component object, even if page caching is
turned on.
A component object’s
init method usually initializes component variables.
For example, in the EmployeeBook example, the
Department.wos script uses
init to initialize the departments component variable:
// WebScript EmployeeBook Department.wos
id departments;
- init {
id departmentsPath;
[super init];
departmentsPath = [[self application]
pathForResourceNamed:@"Departments" ofType:@"array"];
departments = [NSArray arrayWithContentsOfFile:departmentsPath];
return self;
}
The component awake method is invoked immediately after the init method
and each time the component object is restored from the page cache. Just
as in
init, you can implement an awake method that initializes component
variables. For example, in the DodgeDemo application, the
Car.wos script
uses
awake to initialize the shoppingCart component variable:
// WebScript DodgeDemo Car.wos
- awake {
shoppingCart = [[self session] shoppingCart];
}
In general, you use init to initialize component instance variables instead of
awake. The reason is that init is invoked only at component initialization time,
whereas
awake is potentially invoked much more than that. If, however, you
want to minimize the amount of state stored between cycles of the request-
response loop, you might choose to initialize component instance variables
in
awake and then deallocate them in sleep (by setting them to nil in WebScript
Komentáře k této Příručce