Table of Contents Previous Section

Accessing WebScript Methods From Objective-C Code

As stated previously, you can mix WebScript and Objective-C code. Often, programmers use WebScript for component logic, and then supply the bulk of the application (the "business logic") in compiled code.

To access Objective-C code from a WebScript file, you simply use the Objective-C class like any other class:

	id myObject = [[MyCustomObjCClass alloc] init];
To access a WebScript object from Objective-C code, you simply get the object that implements the method and send it a message. If you're accessing a method in the application or session script, you can use WOApplication methods to access the object:

	[[WOApplication application] applicationScriptMethod];
	[[[WOApplication application] session] sessionScriptMethod];
To access a component's methods, you must store the component in the session and then access it through the session. For example, suppose you wanted to rewrite the SelectedCars component of the DodgeDemo so that its database fetch code was in a compiled object and that object directly set the value of the message variable in the SelectedCars component. You'd add the following statement to the init method SelectedCars.wos:

	/* Store the component in the session. */
	[self.session setObject:self forKey:@"SelectedCars"];
and then you can access it in you custom object's fetchSelectedCars method this way:

	/* Get the component from the session. */
	WOComponent *selectedCarsPage = [[[WOApplication application]
		session] objectForKey:@"SelectedCars"];

	/* Send it a message. */
	[selectedCarsPage setMessage:@"You must supply a name and address"];
To avoid compiler warnings, you should declare the scripted method you want to invoke in your code. This is because scripted objects don't declare methods-their methods are parsed from the script at runtime. If you don't declare their methods in your code, the compiler issues a warning that the methods aren't part of the receiver's interface.

Note: This step isn't strictly required-your code will still build, you'll just get warnings.

For the example above, you'd add the following declaration to your object's implementation (.m) file:

	@interface WOComponent (SelectedCarsComponent)
	- (void)setMessage:(NSString *)aMessage;
	@end
While it's certainly straightforward to access a scripted object's methods from Objective-C code, you may not want to have that degree of interdependence between your scripts and your compiled code. You may want to minimize the interdependence to facilitate reusability.