One of our readers contacted me about an apparently weird behavior he was seeing: when running the code from our tutorial the MTLLibrary returned nil after a few hundred draw calls. That made me realize I was not taking into consideration the fact that some of the Metal objects are transient and some are not, according to the Metal documentation. Thanks Mike for bringing this to my attention!
To deal with this matter, we need to re-organize the code, again! And that is always a good thing to do. We need to get the non-transient Metal objects (devices, queues, data buffers, textures, states and pipelines) out of drawRect(_:) and put them in a method that only runs once when the view loads. The command buffers and encoders are the only two transient objects designed for a single use, so we can thus create them with each draw call.
We will pick up where we left off in part 5 of the series. To start, let’s create a new method – an initializer – that only runs once when the view is loaded:
Next, delete the render() method as well as its call inside drawRect(_:) as we don’t need it anymore. Then move all the code from sendToGPU() to drawRect(_:) and delete sendToGPU() as we don’t need this one either. This way we moved all the non-transient objects away from drawRect(_:) and only kept the command buffer and encoder inside, which are the only two transient objects.
Finally, let’s create a new class named MathUtils and move both structs to it so we have a cleaner view class.
Run the program to make sure you are still seeing the glorious triangle as we have seen it in the previous part. The source code is posted on Github as usual.