Tarun Bhargava
Tarun Bhargava

Reputation: 49

How does ARC work in the following code snippet in ios?

Let's say I have a method that returns an object pointer

-(MyObj *) returnMyObj {
   MyObj *obj = [MyObj alloc] init];
   return obj;
}

If I call this function without assigning the pointer like this

Scenario 1

[self returnMyObj];

and if I call this function with assignment to a pointer like this

Scenario 2

MyObj* obj = [self returnMyObj];

Compiler can release the object at the end of the returnMyObj method call in the Scenario 1 but it cant do the same in Scenario 2.How does ARC decide if it needs to retain the created object at the end of method invocation or not in both cases?

Upvotes: 0

Views: 107

Answers (2)

gulyashki
gulyashki

Reputation: 459

Here is what the ARC article in the documentation has to say:

To make sure that instances don’t disappear while they are still needed, ARC tracks how many properties, constants, and variables are currently referring to each class instance. ARC will not deallocate an instance as long as at least one active reference to that instance still exists.

To make this possible, whenever you assign a class instance to a property, constant, or variable, that property, constant, or variable makes a strong reference to the instance. The reference is called a “strong” reference because it keeps a firm hold on that instance, and does not allow it to be deallocated for as long as that strong reference remains.

ARC decides which objects will be kept in memory and which will be deallocated by counting the strong references to the objects.

In your second scenario you are creating a strong reference to the MyObj instance and ARC will not deallocate it while the object is in use. In this case it will be deallocated when the method that uses this object finishes.

Upvotes: 2

Rob Napier
Rob Napier

Reputation: 299345

The optimizer may absolutely release the object in scenario 2 at the end of the statement if obj is not referenced later in the block.

The whole point is that the optimizer can see when the pointer is referenced, and may release it as soon as the last reference is completed. obj does not have precise lifetime semantics, so it only extends the life of the object until the last time obj is referenced, not when obj goes out of scope.

In scenario 1, the reference is not assigned to any variable, so it clearly has no later references, and may be immediately released. That said, it may not immediately release the object, since returnMyObj does not transfer ownership to the caller (due to its name). So the object may not actually be released until the autorelease pool drains.

Upvotes: 1

Related Questions