I am wondering what are the recommended ways of handling situations when a specific owner did not belong in a managed memory object, i.e. objects released by themselves. One such example would be a subclass of NSWindowController, which configures, displays, and controls the input and output of a single window. The controller object displays the window and is released later at some point (usually when the window or sheet that it controls closes). AppKit also provides some examples: NSAnimation saves itself in startAnimation and releases itself when the animation is complete. Another example is NSWindow, which can be configured to release on close.
When implementing these βstand-aloneβ objects, I see at least three different types of GC-safe, but they all have some drawbacks.
but). Using CFRetain / CFRelease.
Autonomous calls of CFRetain objects on itself before it starts its work (for example, in the example of the controller window before displaying the window). Then it calls CFRelease () on itself when it is done (for example, in the example of the controller window after closing the window).
Pros: the user does not need to worry about memory management. Cons: a bit ugly as it requires the use of memory management functions, although we use GC in pure ObjC code. If CFRelease () is not called, the leak can be difficult to find.
b) Prevention of self-ownership idioms with a static data structure.
An object adds itself to the data structure (for example, a static mutable array) before it starts its work and removes itself from there when it is done.
Pros: the user does not need to worry about memory management. No memory management function calls. Objects have an explicit owner. Potential leaks are easy to find.
Cons: locking is necessary if objects can be created from different threads. Additional data structure.
from). Avoid the property idiom by requiring the user of the object to maintain a link to the object (for example, in ivar).
Pros: no calls to memory management functions. Objects have an explicit owner.
Cons: The user of the object must keep the link, even if he no longer needs the object. Additional Ivars.
What pattern would you use to handle these cases?
garbage-collection objective-c cocoa
Nikita Zhuk
source share