hzxu
hzxu

Reputation: 5823

NSObject: retained, removed from array and returned with autorelease, what to do for ARC?

I have the following piece of code:

NSObject *anObject = [[objArray lastObject] retain];
[objArray removeLastObject];
return [anObject autorelease];

With ARC I cannot use retain or autorelease, but if I:

NSObject *anObject = [objArray lastObject];
[objArray removeLastObject];
return anObject;

isn't anObject reaching a 0 retain count when it is removed from array?

I found: What's the equivalent of '[[something retain] autorelease]' in ARC? but it does look like the same situation.

Upvotes: 0

Views: 447

Answers (2)

rmaddy
rmaddy

Reputation: 318954

Your second block of code is fine because the local variable 'anObject' is a strong reference. This code would only be a problem if you declared 'anObject' to be a weak reference.

Upvotes: 0

F.X.
F.X.

Reputation: 7327

Basically, anObject is not released because it is still used in the return statement.

What ARC does is look at your code, decide where you are using each variable, and insert corresponding retain and release calls behind the hood while compiling your code into an executable.

If you want to make absolutely sure that a variable survives through a critical section (although there's very rarely a need for that, and certainly not here), then you can declare it explicitely as __strong. But make sure you understand what are the relationships between your objects, because you can easily create retain cycles and memory leaks by defeating the purpose of ARC.

Upvotes: 2

Related Questions