Home > Articles > Programming > C/C++

  • Print
  • + Share This
From the author of

A protocol defines a set of methods that an object supports. A few new keywords are allowed in protocol declarations for use with distributed objects. These are: oneway, in, out, inout, bycopy, and byref. The first one is used as a modifier on void returns, like this:

- (oneway void)doSomething;

When you send a message to an object normally, you create a new stack frame, call it like a function, and then continue when it's returned. With distributed objects, you send the invocation and then wait for the return. If the method returns nothing then waiting is not always necessary. In general, you can declare any void-returning method as oneway unless it may thrown an exception that you want to catch.

The remaining keywords all apply to parameters. The next three describe pointers. The default is inout, so you never need to specify it (although you might want to for documentation purposes. When you pass a pointer as an argument to message, DO will copy the pointee to the remote end, call the method, and then copy the pointee back over the original pointee value. Specifying in or out will skip one of these copy operations, which can make things faster.

The final two only apply to object arguments or return values. The default is byref, meaning that a proxy will be created on the remote end. Specifying bycopy imposes some extra constraints. The argument must conform to the NSCoding protocol, allowing it to be serialized for copying, and the remote end must have the object's class loaded. Note that this is not a constraint for objects passed by reference: you can access an object via a proxy even without that object's class being loaded or even available on the same computer.

Although these keywords are recognized by the compiler, they have almost no impact on code generation. The only thing that the compiler does with them is encode them in the type string associated with the method in the protocol's metadata. They are interpreted by NSDistantObject.

When you have an instance of NSDistantObject, you can assign a protocol to it by sending it a -setProtocolForProxy: message. This will use the types defined in the protocol definition, where available, instead of the ones found by passing a -methodSignatureForSelector: message to the remote object, which saves some overhead.

You can also use protocols to restrict the methods in an object that you are exposing. The NSProtocolChecker class is another proxy that supports this. Messages sent to this proxy are checked against a protocol and forwarded to the real object only if they are declared in the protocol. This is helpful when you only want to allow (potentially untrusted) remote clients to access a small number of an object's methods.

  • + Share This
  • 🔖 Save To Your Account