The garbage collector invokes this method on the receiver before disposing of the memory it uses.
Deprecated
Garbage collection is deprecated in OS X v10.8; instead, you should use Automatic Reference Counting—see Transitioning to ARC Release Notes.
SDKs
- iOS 2.0–10.0Deprecated
- macOS 10.4–10.12Deprecated
- Mac Catalyst 13.0–13.0Deprecated
- tvOS 9.0–10.0Deprecated
- watchOS 2.0–3.0Deprecated
Framework
- Objective-C Runtime
Declaration
func finalize()
Discussion
The garbage collector invokes this method on the receiver before disposing of the memory it uses. When garbage collection is enabled, this method is invoked instead of dealloc
.
You can override this method to relinquish resources the receiver has obtained, as shown in the following example:
- (void)finalize {
if (log_file != NULL) {
fclose(log_file);
log_file = NULL;
}
[super finalize];
}
Typically, however, you are encouraged to relinquish resources prior to finalization if at all possible. For more details, see Implementing a finalize Method.
Special Considerations
It is an error to store self
into a new or existing live object (colloquially known as “resurrection”), which implies that this method will be called only once. However, the receiver may be messaged after finalization by other objects also being finalized at this time, so your override should guard against future use of resources that have been reclaimed, as shown by the log
statement in the example. The finalize
method itself will never be invoked more than once for a given object.
Important
finalize
methods must be thread-safe.