iOS - Memory Management
Memory management in iOS was initially non ARC(Automatic reference counting) where we have to retain and release the objects. Now it supports ARC where we don't need to add retain and release. Actually the Xcode takes care of the job automatically in compile time.
The two major problems faced as per apple documentation are,
- Freeing or overwriting data that is still in use. This causes memory corruption, and typically results in your application crashing, or worse, corrupted user data.
- Not freeing data that is no longer in use causes memory leaks. A memory leak is where allocated memory is not freed, even though it is never used again. Leaks cause your application to use ever-increasing amounts of memory, which in turn may result in poor system performance or (in iOS) your application being terminated.
Memory Management rules
- We own the objects we create and we have to subsequently release them when they are no longer needed.
- Retain can be used t gain ownership of an object that we did not create. We have release these objects too when it's not needed.
- Don't release the objects that we don't own.
Handling memory in ARC
You don't need to use release and retain in ARC. So, all the view controller's objects will be released when the view controller is removed. Similarly any objects sub objects will be released when they are released. Remember if other classes have strong reference to an object of the class then the whole class won't be released. So it is recommended to use weak properties for delegates.
Using memory management tools
We can analyze the usage of memory with the help of Xcode tool Instruments. It includes tools like activity monitor, Allocations, leaks, zombies and so on.
Steps for analyzing memory allocations
1. Open an existing application.
2. Select Product and then Profile as shown below.
3. Then select Allocations in the next screen shown below and select Profile.
4. We will see the allocation of memory for different objects as shown below.
5. You can switch between view controllers and check whether the memory is released properly.
6. Similarly instead of Allocations we can use Activity Monitor to see the overall memory allocated for the application and it's shown below.
7. These tools help in knowing how much we use and what the places possible leaks have occurred.