Pregunta

I'm working on writing my own Objective C wrapper around a minimal set of OpenAL functionality. One use case I'm trying to enable is transport controls after telling a sound to play like pause/stop/resume operations. I'm interested in trying to do this using what has been described to me as an "opaque type" or an id that conforms to a protocol in Objective C lingo. Does returning one of these make sense in this case, or would it be easier to just directly return an object and tie myself to that implementation?

And assuming the opaque type is the right approach, what would be a good name for the protocol? Right now I'm following this paradigm and calling the protocol OpenALPlaybackDelegate. I feel as if delegate doesn't really quite fit the model since the communication is happening the other way around.

¿Fue útil?

Solución

An opaque type in this case is basically just a pointer that's used in Apple's C APIs in place of an object. Unlike a normal pointer to a struct full of stuff in C, the opacity in 'opaque types' comes from the fact that the header files don't expose the struct definition. The only way to deal with them is through the C functions that are exported. You see this in two places:

  1. C APIs: Core Graphics, Core Audio, Core Foundation, Grand Central Dispatch. C has no objects. Apple has a bunch of types like CGFoobarRef that represent pointers to some sort of thing made with a function like CFFoobarMake();

  2. Bridged APIs. Cocoa functionality is made available to C code through "the toll-free bridge", so you can generally get a handle on a say an instance of a Cocoa class in C world as an opaque type. Again, these generally end with Ref. All the Cocoa container classes, for instance, are available to C consumers through the Core Foundation toll-free bridge.

Relevant Apple documentation

If the consumers of your protocol are Objective-C libraries, which I'm going to assume they are, because that's the only way to use protocols, then no, it doesn't really make sense to expose access to any of your stuff as an pointer to a C struct filled with data and function pointers that are hidden from client code and exposed through a set of C functions.

Also, the reason to do this, for Apple, is encapsulation, data-hiding, etc. All it does is keep people from being able to muck about directly with the internal state of an object from C land, or write code that depends on it, because C lacks features like classes and ivars (well, Objective-C doesn't really have private ivars either but it at least has secret ones).

I would think writing an Objective-C wrapper around OpenAL, exactly what you would not want to do is return opaque types. You should return Objective-C objects that hold opaque type references with accessors/mutators that call the relevant functions on those references.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top