- Objective-C Memory Management Essentials
- Gibson Tang Maxim Vasilkov
- 379字
- 2021-07-23 20:09:12
What's a memory leak and why pay attention to it?
A memory leak is when your program loses track of a piece of memory that was allocated and has forgotten to release it. The consequence is that the "leaked" memory will never be freed by the program. When more memory is leaked after a certain point in time, there will be no more free memory and this will cause your application to crash. Usually, this tends to happen when a piece of code does new
, malloc
, or alloc
, but never does a corresponding "delete", "free", or "release" respectively.
When you do new
, malloc
, or alloc
, what the operating system does is that it is giving your program a chunk of memory on the heap. The OS says, "Here, take this memory address and have this block of memory on it." Thus, you need to create a reference to that memory address (usually in the form of a pointer), depending on the OS, such as, "I'm done with this, it's not useful anymore" (by calling "free", "delete", or "release").
Memory leaks happen when you throw away your pointer to that memory. If your program does not retain where your memory is allocated on the heap, how can you even free it? The following line of code shows an example of a memory leak if you never call the release method on it:
NSMutableString *str = [[NSMutableString alloc] initWithString:@"Leaky"];
So why should you care? At best, you're the dissipating memory that will be freed when the user quits your app. At worst, there could be a memory leak that happens in every screen. It would not be a great mode to end up your program, especially if the user lets it run for a long time. A program crash is very hard to debug as it can crash at random moments in your application as memory leaks are very unpredictable to replicate and creating an application that crashes often will lead to bad reviews of your program on the App Store, or through word of mouth, which is something that you do not want to happen.
This is why in the process of evolution, there are other methods of memory management in Objective-C, which you will find further in this book.
- 玩轉Scratch少兒趣味編程
- Node.js 10實戰
- Learning Real-time Processing with Spark Streaming
- C語言程序設計
- ADI DSP應用技術集錦
- SharePoint Development with the SharePoint Framework
- 算法訓練營:提高篇(全彩版)
- Python面向對象編程:構建游戲和GUI
- Python機器學習算法與實戰
- The Complete Coding Interview Guide in Java
- Terraform:多云、混合云環境下實現基礎設施即代碼(第2版)
- C# and .NET Core Test Driven Development
- Django Design Patterns and Best Practices
- 大數據時代的企業升級之道(全3冊)
- Hacking Android