How can a CAShapeLayer continue drawing on a path (CGPathRef) even though the CGPathRef was released?

98 views Asked by At

I have this code:

   CGPathRef cgPath = [path quartzPath];
   self.blackLine.path = cgPath;
   self.whiteDashes.path = cgPath;
   CGPathRelease(cgPath);

We set the CAShapeLayers (self.blackLine and self.whiteDashes) path to this CGPathRef

Then immediately release the path

But why do the shapelayers still draw the correct path? When you assign the path property does it make a copy? Or does it have to do with the ref or reference key suffix?

1

There are 1 answers

0
Ken Thomases On

It's fine to be curious, but, in terms of a general philosophy of programming with Apple's APIs, the important thing to remember is that you don't have to care. Memory management is designed so each component only has to take a local perspective. You work to get your part right and rely on other components getting their part right and that's enough to make everything work properly.

In other words, you can rely on CAShapeLayer doing what it needs to do in the setter for its path property without needing to know the details. In fact, the details are private to the implementation, so you can't really know them. And, even if you delve under the hood to investigate them, they could change in some future implementation, because there's no design contract that prevents it.

That said, it almost certainly makes a copy using CGPathCreateCopy() or something similar. It could protect against deallocation of the path by retaining it using CGPathRetain() (which it would then have to balance with a future call to CGPathRelease()), but that wouldn't be enough to protect it against the caller passing a mutable path and subsequently mutating it. Making a copy protects against both.