It feels like fleets of new developers dash themselves upon the rocky shores of
Objective-C memory management every day on StackOverflow. I can’t bear to write
the same answers over and over again, so this article will be my final,
unabridged explanation of: retain
, release
, autorelease
, alloc
,
dealloc
, copy
, and NSAutoreleasePool
. There will be some rules to
memorize, but we will also take a journey under the hood for a deeper
understanding.
This article is intended for people who are new to Objective-C, or who never fully learnt how manual reference counting works. It does assume that you have some programming experience, possibly in another language. If you are a beginner programmer and Objective-C is your first language, I will try to keep the explanations clear, but it may become confusing the more in-depth we get.
We will be covering:
- A Quick Mention Of ARC And Garbage Collection
- Coming From C/C++
- Coming From a Garbage Collected Language (Java, Python, C#, etc.)
- What Is Reference Counting?
- How Does Reference Counting Work In Objective-C?
-
NSAutoreleasePool
Andautorelease
- Common Mistakes
If something is not explained, or not explained very well, post a question in the comments and I’ll expand the article to cover it.