- A Simple Example
- Java Class
- Java Header
- Setting up Java
- Objective-C Class
- Conclusion
Objective-C Class
The final piece of this application is the AppDelegate class itself. The one unusual thing that the AppDelegate needs to do is to initialize the URLRetriever. Once the URLRetriever is initialized, it can be treated as if it were a normal Objective-C class. The following is the implementation of the AppDelegate:
#import "AppDelegate.h" #import "URLRetriever.h" @implementation AppDelegate - (id)init { if (![super init]) return nil; Class javaClass = NSClassFromString(@"URLRetriever"); javaObject = [[javaClass alloc] init]; return self; } - (IBAction)retrieveAction:(id)sender { NSString *url = [urlField stringValue]; if (![javaObject setURL:url]) { NSLog(@"Bad url..."); NSAlert *alert = [[[NSAlert alloc] init] autorelease]; [alert addButtonWithTitle:@"OK"]; [alert setMessageText:@"Invalid URL"]; [alert setAlertStyle:NSWarningAlertStyle]; [alert beginSheetModalForWindow:window modalDelegate:self didEndSelector:nil contextInfo:nil]; [urlField selectText:self]; return; } [self willChangeValueForKey:@"source"]; [source release]; source = [[javaObject retrieveSource] retain]; [self didChangeValueForKey:@"source"]; } - (NSString *)source { return source; } - (void)dealloc { [source release]; [javaObject release]; [super dealloc]; } @end
The init: method is of particular interest in this class because it is where the Java object is initialized. In this method, the Java class itself must first be referenced, and then alloc and init is called on it. This will initialize an instance of the class to be used. The NSClassFromString function searches the classpath and finds the appropriate Java class, returning a pointer to it.
Notice that when you are utilizing a Java class inside of an Objective-C class, it needs to be retained and released just as any other Objective-C class. Java's memory management does not apply. Conversely, if you were using an Objective-C class inside of a Java application, it would not be necessary to retain/release the objects because Java's Garbage Collector would handle it.