3

Let's say I want to create a temporary variable, e.g.:

  1. To point to another long-living variable:

    __unsafe_unretained UIView *tableHeaderView = self.tableView.tableHeaderView;
    
  2. To point to an object I just created.

    __unsafe_unretained UIView *tableHeaderView = [[UIView alloc] init];
    

These temporary variables don't need to be retained because the objects they point to are guaranteed to keep positive retain counts for as long as the temporary variables are in scope. So, should I declare them as __unsafe_unretained?

ma11hew28
  • 121,420
  • 116
  • 450
  • 651
  • 1
    What Joshua and zoul said. The hit from the extra retain/release is insignificant for the issue prevention you get. – Wevah Jan 26 '12 at 15:13

3 Answers3

5

Why does it matter if the system retains your temp variable? And as a matter of fact, you DO want to retain it.

Consider:

__unsafe_unretained UIView *tableHeaderView = self.tableView.tableHeaderView
self.tableView.tableHeaderView = nil;
NSLog(@"%@", tableHeaderView); //<-I WILL CRASH
Joshua Weinberg
  • 28,598
  • 2
  • 97
  • 90
  • Only for performance reasons. It seems like the compiler should be smart enough not to retain a temp variable if it doesn't have to. – ma11hew28 Jan 26 '12 at 15:17
  • 2
    It can't reasonably know though. What if instead of setting it nil directly there, I called some other method which triggered a long chain of events resulting in tableHeaderView being released? Also, you're pre optimizing. If retaining of objects is EVER your top concern for performance, you've already done tons of other stuff. Object ownership is not going to be your choke point. – Joshua Weinberg Jan 26 '12 at 15:21
2

Matt,

The whole point of ARC is to let you ignore these kinds of issues. In fact, the complier may not even retain these instances.

Let ARC worry about these issues. Don't try to help it until the compiler or the static analyzer complain. (BTW, you are letting the analyzer run with every compile, right? It finds problems as you create them.)

You should only worry about excess object creation in loops and managing the creation of large objects. The former is handled by judicious use of @autorelease. You still manage large items as you did ante-ARC.

Andrew

adonoho
  • 4,339
  • 1
  • 18
  • 22
1

No. If ARC retains it, it will let go when the variable goes out of scope.

zoul
  • 102,279
  • 44
  • 260
  • 354