Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autorelease vs. release

When I need an array for temporary use, what's the difference between these:

1:

NSMutableArray *stuff = [[NSMutableArray alloc] init];
// use the array
[stuff release];

2:

NSMutableArray *stuff = [NSMutableArray array];
// use the array

3:

NSMutableArray *stuff = [[[NSMutableArray alloc] init] autorelease];
// use the array

I prefer number 2, since it's shorter. Are there any good reasons to use number 1 or 3?

like image 626
keronsen Avatar asked Nov 02 '10 11:11

keronsen


People also ask

What is autorelease?

Overview. An autorelease pool stores objects that are sent a release message when the pool itself is drained. Important. If you use Automatic Reference Counting (ARC), you cannot use autorelease pools directly. Instead, you use @autoreleasepool blocks.

What is Dealloc in C?

-dealloc is an Objective-C selector that is sent by the Objective-C runtime to an object when the object is no longer owned by any part of the application. -release is the selector you send to an object to indicate that you are relinquishing ownership of that object.

Which of the following do you use to deallocate memory Dalloc () Dealloc () Release () free ()?

Free is used to deallocate the memory allocated by malloc, calloc.


1 Answers

Number 2 is likely the best choice in most cases.

Number 1 has the chance of losing the release at some point down the line, for whatever reason, but it does release the array immediately, which in memory-starved environments can be useful.

Number 3 is basically a verbose equivalent of number 2, but it does come in handy if you want to use an initWith* that doesn't have a corresponding arrayWith*.

Note: If you are memory-starved, such as in an expensive loop where you need a fresh array for each iteration; don't release and allocate new arrays; just use -removeAllObjects and recycle the array.

like image 110
Williham Totland Avatar answered Sep 28 '22 07:09

Williham Totland