Object Lifecycle¶
The main objects described in Object Model can be created with dedicated plug-in methods, or with wrapper methods offered by the Q2PixLib component. The plug-in also offers a method for destroying these objects. Let’s see now who is responsible for destroying these objects.
Consider the following scenario:
- A form method creates an Image Document object.
- The form method assigns the object to an Image Area.
- The form contains buttons that allow the user to rotate the image right or left in the area.
- The form also contains a button that starts a new 4D process that displays information about the Image Document in a window.
Every entity involved in this scenario (the form method, the plug-in area, the form object method) needs to keep around a reference to the Image Document. But who is responsible for destroying it in the end?
Now consider a second scenario:
- A project method attached to a menu item presents the standard file selection dialog allowing the user to select an image file.
- After the user selects a file, the project method verifies that the selected file is a readable image by creating an Image Document object with the selected file.
- After verification succeeds, the project method passes the image document reference to a new process for processing or display.
Again: who is responsible for destroying the document reference in the end?
In both scenarios the answer comes from a common programming technique called Reference Counting. Reference counting provides (i) a clear distinction of roles and responsibilities among the entities involved in object lifecycle management, and (ii) maximum data sharing among these entities without data duplication.
Here’s how it works:
- Every object has an integer attribute called retain count – or reference count.
- When an object is created its retain count is set to
1
.- Entities that need to keep around a reference to the object (clients), increase its retain count by
1
.- When clients no longer need the object, they decrease the retain count by
1
.- When the retain count of the object becomes
0
, the object is destroyed.
It may sound somewhat complicated, but in fact it is not.
Regarding reference counting in Q2Pix objects, just follow this simple rule:
Q2Pix Reference Counting Rule
Every object reference returned either as the result of a method, or through
a method parameter, must be released with a call to
ImgObj_Release
when no longer needed.
The ImgObj_Release
plug-in method decrements the retain count. When the retain count becomes 0
, the object is destroyed.
Other plug-in methods for managing object lifecycle are ImgObj_Retain
(increases the retain count; allows clients to keep reference to the object without duplication)
and ImgObj_GetRetainCount
(returns the retain count – very useful in debugging).
See Managing Object Lifecycle in Programming Guide for sample 4D code implementing this scenario.