4

Does the automatic reference counting release an object if I set the pointer to nil or assign the pointer to another object?

For example doing something like that:

//in .h file

@interface CustomView : UIView
{
   UIView *currentView;
}


// in .m file:

-(void)createView1
{
   currentView = [[UIView alloc] init];
   [self addSubview:currentView];
}

-(void)createView2
{
   [currentView removeFromSuperview];

   // does the former view get released by arc
   // or does this leak?
   currentView = [[UIView alloc] init];
   [self addSubview:currentView];
}

If this code leaks, how would I declare *currentView properly? Or how would I make ARC "release" the currentView? thanks!

Ben Lings
  • 28,823
  • 13
  • 72
  • 81
DrElectro
  • 83
  • 2
  • 5
  • possible duplicate of [Dangling pointers in objective c - does nil also release memory?](http://stackoverflow.com/questions/20873253/dangling-pointers-in-objective-c-does-nil-also-release-memory) – jscs Jan 01 '14 at 21:30

2 Answers2

6

With ARC you don't need to think about release/retain.

Since your variable will have been implicitly defined as strong there's no need to set it to NULL - it'll be released before it's assigned to.

Personally though I prefer to declare properties:

@property (strong, nonatomic) UIView *currentView;
Navnath Godse
  • 2,233
  • 2
  • 23
  • 32
tarmes
  • 15,366
  • 10
  • 53
  • 87
  • I like your answer better (and +1, too)... while what I suggested in my answer seems like good coding style, I've been trying to find any reference in [Apple's ARC documentation](http://developer.apple.com/library/ios/#releasenotes/ObjectiveC/RN-TransitioningToARC/_index.html#//apple_ref/doc/uid/TP40011226-CH1-SW4) to prove one way or another. – Michael Dautermann Nov 27 '11 at 13:42
  • 2
    `nil`. FYI - http://stackoverflow.com/questions/557582/null-vs-nil-in-objective-c – beryllium Nov 27 '11 at 13:43
  • thanks! i was pretty unsure about that.. but it really makes sense! ;) – DrElectro Nov 27 '11 at 14:04
3

After doing [currentView removeFromSuperview], you should call currentView = nil and ARC will do it's release magic. You can then reassign currentView with that new UIView there.

Michael Dautermann
  • 88,797
  • 17
  • 166
  • 215