Clients
The client for this example is exceedingly simple. I created a generic Cocoa application from the template supplied with XCode by following these steps:
- Opening XCode and selecting a new project.
- Selecting Cocoa Application.
- Giving it a descriptive name.
- Creating a class named AppDelegate.
- Opening the MainMenu nib and dragging the AppDelegate.h file to Interface Builder.
- Instructing Interface Builder to instantiate AppDelegate.
- Dragging and dropping an instance of NSTableView to the main window of the application.
- Adding a third column to the table view.
- Dragging and dropping an instance of NSArrayController to the application.
- Setting the NSArrayController’s content array to "customers" on the AppDelegate.
- Setting the columns in the NSTableView to point to "name", "guid", and "createDate".
- Adding a date formatter to the third column.
After everything is in place, the only thing left to do is write the code that calls the servlet and retrieves the XML file.
#import <Cocoa/Cocoa.h> @interface AppDelegate : NSObject { NSArray *customers; } - (NSArray *)customers; - (void)setCustomers:(NSArray *)aCustomers; @end
In this header file, there is only one variable added to the class: the NSArray that I populate from the servlet. In this example I populate the array directly from the init method of the AppDelegate. (In a production system it is better to do this after the application has initialized and perhaps even in a separate thread.)
#import "AppDelegate.h" @implementation AppDelegate - (id)init { if (![super init]) return nil; [self setCustomers:[NSArray arrayWithContentsOfURL:[NSURL URLWithString:@"http://www.zarrastudios.com/example/customerList"]]]; return self; } - (NSArray *)customers { return customers; } - (void)setCustomers:(NSArray *)aCustomers { [customers release]; customers = [aCustomers retain]; } @end
In the init method of the AppDelegate, it is a single method call to the servlet, and the results can be passed directly into the NSArray. Because the xml file is a valid plist, the NSArray can read it directly.
That is all there is to it from the client side of things. The reverse of this procedure, posting to a servlet, is nearly as straightforward. In that situation, it is just like posting to any Web page. By utilizing a NSMutableURLRequest it is possible to post any type of data to a servlet. Because NSArray objects and NSDictionary objects can be written out to xml, it is easy to send even fairly complex data to a servlet with relatively little code.