The Wayback Machine - https://web.archive.org/web/20241009063457/https://www.geeksforgeeks.org/memory-management-in-objective-c/
Open In App

Memory Management in Objective-C

Last Updated : 06 Dec, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Memory management is a core concept irrespective of any programming language. The process of allocation of memory of objects when needed and deallocation when they are no longer in use is called Memory Management. Memory is a limited resource and so has to be dealt with carefully. If unrequired memory is not freed gradually you run out of memory leading to the suffering performance of your computer and in worst-case scenarios it can even crash your computer. Efficient Memory management concerns us with time, cost, and resource-saving which can be achieved in Objective-C fairly.

In Objective-C memory is managed as follows: 

  1. MRR (Manual Retain Release)
  2. ARC (Automatic Reference Counting)

Manual Retain Release(MRR)

MRR(Manual Retain Release) is also known as Manual Reference Counting(MRC). In Objective-C, all classes are derived from the root class NSObject (here, NS stands for NeXTSTEP) which provides methods for memory management. All NSObject classes are reference counted i.e Objects keep a track of how many times they are referenced by another object. When the reference count turns zero, the object dies and the memory is deallocated.
Retain (Reference count ++) and Release(Reference count –) are special methods that are used to keep track of reference count, where Retain method increases the value of reference count by 1 and the Release method decreases the value of reference count by 1.
According to the MRR technique, we directly manage memory by allocating and deallocating it manually. Therefore, if an object is created it does not die until we do not destroy it. In case, if we create an object and forget to destroy or release the object, it causes Memory Leakage. We may run out of memory if it continues to leak.

MRR BASIC RULES

In MRR, as the name suggests everything is done manually from creating an object, accessing it, retaining an object, releasing it, and destroying the object. Therefore, in order to avoid memory leakage and to the exact track of the reference count there are a few basic rules to remember:

  1. One who creates the object is the owner of the object itself. “alloc”, “new”, “copy” or “mutableCopy” methods are used to create an object and imply you have ownership of the object as well.
  2. One can own an object using retain method. Sometimes methods apart from “alloc”, “new”, “copy” or “mutableCopy” return an object, in that case since you didn’t create the object and so you don’t have ownership of it. But the ownership can be achieved by using the “retain” method as if you have obtained the object with the “alloc” / “new” / “copy” or “mutableCopy” method. Also, if an object is retained x number of times then it has to be released x number of times.
  3.  One must relinquish ownership of an object being owned by using the release or autorelease method when the object is no longer in use. The release method releases the object immediately whereas the autorelease method does not releases the object immediately but sends it into an autorelease pool and releases the object when the pool is drained.
  4. One must not release an object not being owned. Releasing an object we don’t own can crash the application. Crash can occur in cases when we release or access an already destroyed object.
Manual Retain Release(MRR)

 

The life cycle of the object of Class X is represented in the above diagram along with the proper implementation of rules:

An object of class X has been created using the “alloc”/”init” method provided in NSObject class. as an object is created and so the reference count turns 1(Rule 1). 

Some Class Y accesses Class X objects. Since class Y does not own the object “retain” method is used to obtain the object. As retain method is used, it increments the value of the reference count by 1, updating the value of the reference count to 2 (Rule 2).

Class X object has been retained twice by two different classes and therefore, in order to destroy the object and to achieve zero reference count it has to be released twice. Firstly, the reference count currently which is 2 is decreased by 1 when Class X releases the object and becomes 1. At last, when Class Y releases the object, the reference count turns zero, destroying the object(Rule 3).

Further, Class Z made another object that is a copy of the Class X object. Here, a new object is created that has the same instance variables as that of the Class X object here, the reference count turns 1(Rule 1).

Class Z used a release method that decreases the value of the reference count by 1. On decrement, the value of the reference count becomes zero and the object of Class Z is destroyed(Rule 3).

ObjectiveC




#import<Foundation/Foundation.h>
  
@interface my_class:NSObject
-(void)my_method;
@end
  
@implementation my_class
-(void)my_method{
    NSLog(@"It's gonna be allocated 😉 \n");
}
-(void)dealloc{
    NSLog(@"Everything's cleaned up 🙂 \n");
    [super dealloc];
}
@end
  
int main()
{
  
      // some_object_gfg has been created
    my_class *some_object_gfg=[[my_class alloc]init];
    [some_object_gfg my_method];
      
    // Reference count = 1
    NSLog(@"Reference count after allocation :%d",[some_object_gfg retainCount]);
    [some_object_gfg retain];
      
    // Reference count = 1+1 = 2
    NSLog(@"Reference count after retain :%d",[some_object_gfg retainCount]);
    [some_object_gfg release];
      
    // Reference count = 2-1 = 1
    NSLog(@"Reference count after release :%d",[some_object_gfg retainCount]);
    [some_object_gfg release];
      
    some_object_gfg = nil;
      
    // Reference count = 0 
      // Object destroyed
    return 0;    
}


Output:

2022-11-28 08:07:12.546 main[55731] It's gonna be allocated ;) 
2022-11-28 08:07:12.546 main[55731] Reference count after allocation :1
2022-11-28 08:07:12.546 main[55731] Reference count after retain :2
2022-11-28 08:07:12.546 main[55731] Reference count after release :1
2022-11-28 08:07:12.546 main[55731] Everything's cleaned up :) 

Automatic Reference Counting(ARC)

ARC(Automatic Reference Count) was introduced by Apple Inc. in 2011 for application development on its desktop and mobile OS, Mac OS X Lion, and iOS 5. ARC is a more advanced, convenient, and automatic way of memory management. ARC itself inserts proper memory management calls like retain, release, and autorelease for users at compile time based on usage. It also follows the same basic rules discussed above but with little modifications like ownership qualifiers. It reduces long code as the developer needs not to write every retain or release. It also minimizes the risk of memory leakage as the compiler evaluates the life of the object itself. Retain, release, autorelease, or retainCount methods only work with MRR and not ARC. Also, errors show up if we use NSAutoreleasePool instead of @autoreleasepool block. The garbage collection principle is only available for Mac OS X, starting with version 10.5. Also, iOS applications can’t use Garbage collection, since it depends on the power of the device, it will take some time to process, forcing the user to wait to lead to a bad user experience. It is also deprecated since OS X Version 10.8 is in favor of ARC and is scheduled to be removed in the forthcoming versions of OS X. ARC is not a runtime service. It doesn’t follow the garbage collection program execution pattern. Apple says, “ARC in Objective-C makes memory management the job of the compiler”.

ObjectiveC




#import<Foundation/Foundation.h>
  
@interface my_class:NSObject
-(void)my_method;
@end
  
@implementation my_class
-(void)my_method{
    NSLog(@"Using ARC : \n");
}
-(void)dealloc{
    NSLog(@"Everything's cleaned up 🙂 \n");
    [super dealloc];
}
@end
  
int main()
{
    @autoreleasepool{
      
          // Compiler takes care of retain , release or 
          // autorelease itself as it is automatic
        my_class *some_object_gfg = [my_class[alloc]init];
        [some_object_gfg my_method];
        some_object_gfg = nil;
    }
    return 0;
}


Note: This code will not run on an online compiler as it does not support ARC.

Output:

Output

AUTOMATIC REFERENCE COUNTING



Similar Reads

Overriding Inherited Methods in Objective-C
Objective-C is an object-oriented programming language that is widely used in the development of iOS and Mac applications. Inheritance is an important concept in object-oriented programming that allows classes to inherit properties and behavior from other classes. In Objective-C, inheritance is the mechanism by which one class acquires properties a
9 min read
Typedef in Objective C
A typedef allows us to define a data type with a new name, for example, typedef unsigned char CAT. Now from now, onwards CAT can be used as an abbreviation for unsigned char, for example, CAT num1, num2;. Or in other words, we can say that typedef is a keyword that is used to assign the new name to the predefined or user-defined datatypes. Thus, yo
3 min read
Blocks in Objective-C
Blocks in Objective-C are a potent tool that can simplify the development process. Blocks are an alternative to traditional functions, allowing you to write code that is more concise and efficient. They are used for many different purposes, including as callbacks and iterators. Blocks can also be used to create custom objects and pass data between
6 min read
Pointers to Structures in Objective C
A pointer is a variable whose value is the address of another variable, e.g., stores the address of the memory location. Like any variable or constant, you must declare a pointer before you can use it to store variable addresses. It simplifies the programs and reduces their length. It is useful for allocating and deallocating memory during program
3 min read
Dates and Times in Objective-C
In Objective-C, dates and times are represented using the NSDate and NSDateFormatter classes. NSDate class represents a single point in time. It stores an absolute point in time, independent of any particular calendar or time zone. You can use NSDate to represent a date and time, or just a date or time by itself. To create a new NSDate object, you
4 min read
Function Call by Value in Objective-C
In Objective-C, "call by value" refers to the practice of passing a copy of a value, rather than a reference to the original value, as an argument to a function or method. This means that any changes made to the value within the function or method do not affect the original value outside of the function or method. In Objective-C, the type of an arg
3 min read
Nested Switch Statements in Objective-C
Like most of the popular programming languages, Objective-C also allows using decision control statements, namely Switch-Case statements. This statement has an expression part, and a cases-value part, where each case contains a unique value. After evaluating the logical expression, the result of that will sequentially get compared with each case on
6 min read
Do While loop in Objective-C
Just like other programming languages Objective-C also supports do..while loop. do..while loop is also known as an inverted while loop because, in a while loop, the expression is evaluated before executing the code present inside the body of the while loop, if the expression is false, then this loop doesn't execute the body of the while loop. Where
3 min read
Fast Enumeration in Objective-C
Fast Enumeration is basically defined as the concept of a collection of data types that contains a fixed set of constants. So they can be used at various places in the programming language. As we know that Objective - C is similar to other programming languages so it supports all the features that were supported by other Programming languages, In O
4 min read
Passing Arrays as Function Arguments in Objective-C
Every programming language has a data structure that is used to store elements. Similarly, Objective-C also supports data structure which is known as an array. An array is used to store elements of the same data types in a fixed-size sequential collection. In an array, you are not allowed to store different types of elements in the same array means
5 min read
Multi-Dimensional Arrays in Objective-C
Arrays are basically defined as linear data structures that are used to store similar types of data elements. Arrays can be single-dimensional or multi-dimensional. As the name suggests that multi-dimensional means it is a data structure that is used to store similar types of data like(integers, floats, characters, doubles, etc) elements in tabular
5 min read
Function Call by Reference in Objective-C
Just like other languages in objective-C also a function is used to perform some specific task. In objective-C, we can call a function by value or by reference. So, in this article, we will talk about the call by reference in Objective-C. The call-by-reference is a process of passing arguments to a function that copies the address of an argument in
3 min read
Decision Making in Objective-C (if, if...else, Nested if)
Like, every programming language, Objective-C also has a decision control statement, namely an if-else statement and a switch statement. These statements help programmers to execute a single or a set of instructions based on a defined condition. If the defined condition evaluates as true, then the statement (or the block of statements) attached wil
7 min read
While loop in Objective-C
Just like other programming languages Objective-C also supports while loop. While loop is a loop that is used to repeat a statement or a group of statements till the given condition is true. Every time while loop checks the condition before executing its body. Or we can say that we can use a while loop when we don't know the exact number of iterati
3 min read
NSArray and NSMutableArray in Objective-C
An array is a data structure that allows to store data in contiguous memory. They can be used to store primitive data types such as int, float, double, char, etc of any particular type or can store derived data types such as structures, pointers, etc. Its indexing starts with 0 i.e. the first element is stored at the 0 index, the second element at
5 min read
NSDictionary and NSMutableDictionary in Objective-C
Dictionary in Objective-C stores objects in a key-value pair. The data items stored in a dictionary can be accessed using its key. It is dynamic in nature means the size of the dictionary grows according to the need. In Dictionary, the key cannot be null, but the value can be NULL. It can be mutable or immutable. Mutability means changeable i.e. if
5 min read
for loop in Objective-C
Like most programming languages, Objective-C also has a repeating statement called for loop. It is a repetition control statement that allows you to repeatedly execute a single instruction or a block of instructions into a specified number of times. unlike other loops like while-loop or do-while loop, for loop has the capability to initialize its a
9 min read
Nested loops in Objective-C
Like most programming languages, Objective-C also gives three basic repetition control statements, namely loops, which help programmers to execute a single or block of statements repetitively till the given condition is satisfied. Furthermore, these loops can be used one inside another which is called a Nested loop. Let's discuss them one by one. T
9 min read
Return Pointer From Functions in Objective-C
A pointer is like a variable or constant that stores the address of another variable. It must be declared before the address value of a variable is to be stored in it. The main advantage of using a pointer is that it frees up the program memory and provides direct access to memory locations. It also allows the manipulation of data which makes the p
5 min read
Return Array From a Function in Objective-C
An array is a form of data structure that has a homogenous collection of data in a fixed size. In a nutshell, an array is a group of variables of the same type. For instance, integers cannot be stored in an array of string types. The lowest address of the first element of the array is 0, while the highest address is reserved for the last element. A
6 min read
Structures in Objective-C
Objective-C is an object-oriented programming language that adds small talk-style messaging to the C programming language. Follows a bottom-up programming approach. It incorporates concepts from both procedural and object-oriented programming languages. Objective-C support structures. So in this article, we will learn about structures and their usa
5 min read
Categories in Objective-C
Categories are an important concept in the Objective-C programming language. They allow developers to extend the functionality of existing classes without having to modify their original code. This article will discuss categories in Objective-C, their uses, and provide examples of their implementation. Categories In Objective-C, categories are a wa
3 min read
Overriding Methods in Objective-C
If a subclass (child class) has the same method name as declared in the parent class, then it is known as method overriding in Objective C. Method overriding is a language feature in which a class can provide an implementation of a method that is already provided by one of its parent classes. The implementation in this class will replaces (that is,
5 min read
Arrays in Objective-C
An Array is a data structure that holds similar types of data in contiguous memory. The Objective-C array is a single variable array that is used to store different types of elements in the array. Also, we can access the objective-c array using an index. It is quite similar to the C programming language. Declaration of an Array To declare an array
5 min read
Command Line Arguments in Objective-C
In Objective-C, command-line arguments are strings of text that are passed to a command-line program when it is launched. They can be used to specify options or parameters that control the behavior of the program or to provide input data that the program can process. To access command-line arguments in an Objective-C program, you can use the argc a
2 min read
Operators in Objective-C
The Objective-C language is developed on top of C Programming. The operator in Objective-C is the same as the C language operators. It is primarily used in developing iOS and MacOS operating systems and software applications for iOS. Operators are used to forming a mathematical expression using variables. To perform an operation on a variable we us
11 min read
Array of Pointers in Objective-C
A pointer is a variable that stores the address of another variable. We use pointers because, with the help of pointers the memory is accessed efficiently, it saves memory space, and execution time is faster as compared to the use of normal variables using stack memory because pointers store their memory dynamically which can be free after the comp
5 min read
Dynamic Binding in Objective-C
As the name suggests Dynamic binding is the process of joining two different things or creating a relation between different things. Or we can say that dynamic binding is a process of determining a method to invoke at runtime, not at the compiler time. Objective - C is a programming language that supports all the concepts so dynamic binding. It is
5 min read
Passing Pointers to Functions in Objective-C
Pointers are a crucial aspect of any programming language and passing pointers to functions in Objective-C is no exception. In Objective-C, pointers are used to pass values between functions and to manipulate memory in a more flexible manner. Pointers can be passed as arguments to functions and can also be returned as function results. Passing poin
3 min read
Constants in Objective-C
Constants in Objective-C are values that cannot be modified once they are set. They are used to store a variety of data types, including numbers, strings, and booleans. Constants are a fundamental feature of the Objective-C programming language and are widely used in the development of applications for Apple's macOS and iOS platforms. They are part
4 min read
Article Tags :