Home > Articles > Home & Office Computing > Mac OS X

  • Print
  • + Share This
From the author of

Offering an object for remote use is very simple. There are three steps involved. First you need to get an NSConnection instance, then associate an object with it, and finally advertise it by associating a name with it.

If you read the Distributed Objects guide on Apple's developer site, it says that you get a connection like this:

connection = [NSConnection defaultConnection];

This works, but as of 10.6 it is deprecated. There are a few obscure cases where this can lead to a race condition. The preferred way now, which also works with earlier versions, is:

connection = [[NSConnection new] autorelease];

You then associate your object with it by passing it as an argument to a -setRootObject: message. A proxy encapsulating that object can then be accessed by anyone on the remote end of the connection. The connection is still anonymous at this stage and is not connected to a network or any other mechanism for sharing it. Before it can be used, you need to use this method:

- (BOOL)registerName: (NSString*)name 
      withNameServer: (NSPortNameServer*)server;

The simpler version of this, -registerName:, calls this with the system default port server. Do this if you just want to share the object with apps on the local machine. If you want to share it on the local network use the shared instance of NSSocketPortNameServer.

Note that port names need to be unique within a port name server. The socket port name server expects names to be unique on the local network, so it's a good idea to add the host or user name (or both) to the port name to avoid conflicts.

Getting (a proxy representing) the vended object is not much harder. NSConnection provides this class method for getting remote objects:

+ (NSDistantObject*)rootProxyForConnectionWithRegisteredName: (NSString*)name
                                                        host: (NSString*)hostName
                                             usingNameServer: (NSPortNameServer*)server;

The arguments are the name, the host to query and the name server to look on. You can then use the returned proxy as if it were the real object. This includes passing it into any other code that is not written with DO in mind, including Cocoa framework code. For example, you can add the proxy to an NSArray and then send it a message with -makeObjectsPerformSelector: or similar.

  • + Share This
  • 🔖 Save To Your Account