Should I use __unsafe_unretained for temp variables?

664 views Asked by At

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?

3

There are 3 answers

0
zoul On

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

2
Joshua Weinberg On

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
0
adonoho On

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