Increments the receiver’s reference count.
Required.
SDKs
- iOS 2.0+
- macOS 10.0+
- Mac Catalyst 13.0+
- tvOS 9.0+
- watchOS 2.0+
Framework
- Objective-C Runtime
Declaration
- (instancetype)retain;
Return Value
self
.
Discussion
You send an object a retain
message when you want to prevent it from being deallocated until you have finished using it.
An object is deallocated automatically when its reference count reaches 0
. retain
messages increment the reference count, and release
messages decrement it. For more information on this mechanism, see Advanced Memory Management Programming Guide.
As a convenience, retain
returns self
because it may be used in nested expressions.
You would implement this method only if you were defining your own reference-counting scheme. Such implementations must return self
and should not invoke the inherited method by sending a retain
message to super
.
Special Considerations
Instead of using manual reference counting, you should adopt ARC—see Transitioning to ARC Release Notes.