Home > Articles > Programming > Java

  • Print
  • + Share This
Like this article? We recommend

Like this article? We recommend

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:

  1. Opening XCode and selecting a new project.
  2. Selecting Cocoa Application.
  3. Giving it a descriptive name.
  4. Creating a class named AppDelegate.
  5. Opening the MainMenu nib and dragging the AppDelegate.h file to Interface Builder.
  6. Instructing Interface Builder to instantiate AppDelegate.
  7. Dragging and dropping an instance of NSTableView to the main window of the application.
  8. Adding a third column to the table view.
  9. Dragging and dropping an instance of NSArrayController to the application.
  10. Setting the NSArrayController’s content array to "customers" on the AppDelegate.
  11. Setting the columns in the NSTableView to point to "name", "guid", and "createDate".
  12. 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.

  • + Share This
  • 🔖 Save To Your Account