Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the automatic reference counting release an object if i set the pointer to nil?

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!

like image 806
DrElectro Avatar asked Jan 18 '23 04:01

DrElectro


2 Answers

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;
like image 77
tarmes Avatar answered Jan 31 '23 00:01

tarmes


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.

like image 43
Michael Dautermann Avatar answered Jan 30 '23 22:01

Michael Dautermann