Archive for August 23, 2003

Saturday, August 23, 2003

NSObjectInaccessibleException

Today I learned something about distributed objects and NSConnection. When I have an object that I want to access from multiple threads (or that I want to receive messages in the main thread), I make it a DO server, and I give each thread a proxy. I’ve been creating the proxies like this:

NSConnection *clientConnection = [[[NSConnection alloc]
                           initWithReceivePort:[serverConnection sendPort]
                                      sendPort:[serverConnection receivePort]];
id proxy = [clientConnection rootProxy];

There is only one serverConnection per server, but that’s OK because I call [serverConnection enableMultipleThreads]. The problem was that I was inexplicably getting NSObjectInaccessibleExceptions saying “NSDistantObject access attempted from another thread” when two threads tried to create proxies for the same server.

The above code makes it look like there’s one clientConnection per thread/proxy. However, the documentation for the -initWithReceivePort:sendPort: method says:

If an NSConnection with the same ports already exists, releases the receiver, retains the existing NSConnection, and returns it.

This means that the connection will be shared among multiple threads and you have to call [clientConnection enableMultipleThreads] to avoid the NSObjectInaccessibleException. I’m not a big fan of this design, because I don’t think code using a given connection should have to know when some other code is using a connection with the same ports. But there you have it.