Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning autoreleased objects using ARC

Assuming that I wrote the code below in a class A:

-(NSArray *) returnListNames {

    NSArray *returnList = [NSArray arrayWithArray:myListNames];

    return (returnList);
}

And in a class B I get that list in some scope in this way:

{
    /* Without ARC I would  retain the array returned from ClassA 
       to guarantee its reference like this:
       [[myClassA returnListNames] retain]; */

    NSArray *myNames = [myClassA returnListNames];  

}

Considering that the returnList was allocated using an autorelease method, how can I guarantee that I won't lose the reference to it using ARC (under which I can't use retain)? Will I have to use [[NSArray alloc] init] on the myNames array? Or I must use alloc on returnList instead of an autorelease method? Or can I just rely on ARC? Or is there another solution?

like image 458
Arildo Junior Avatar asked Oct 30 '11 19:10

Arildo Junior


People also ask

What method is automatically called to release objects?

The destructor is only one way to destroy the object create by constructor. Hence destructor can-not be overloaded. Destructor neither requires any argument nor returns any value. It is automatically called when object goes out of scope.

How ARC works in Objective C?

Automatic Reference Counting (ARC) is a memory management option for Objective-C provided by the Clang compiler. When compiling Objective-C code with ARC enabled, the compiler will effectively retain, release, or autorelease where appropriate to ensure the object's lifetime extends through, at least, its last use.

What method is automatically called to release objects in IOS?

About Autorelease Pool Blocks // Code that creates autoreleased objects. At the end of the autorelease pool block, objects that received an autorelease message within the block are sent a release message—an object receives a release message for each time it was sent an autorelease message within the block.

What method is automatically called to release object in Swift?

What is ARC? Now swift use ARC to automatically allocating and deallocating memory. In this method, You don't need to use release and retain. The core concept of ARC is very simple, an object is retained in memory by incrementing the reference count and then released by decrementing that same count.


1 Answers

ARC will handle this for you, so you can just rely on it and go about your business with that array. If it sees that you need to retain myNames, it will add a retain call for you for example, or do whatever else it actually does when you compile the code that uses it.

like image 166
BoltClock Avatar answered Nov 15 '22 15:11

BoltClock