1

I am new to iPhone Development. I have taken UIView,UIImageView,UIScrollView etc in my NIB File. My question is that can i remove all that views from SuperView ? For Example:`

-(void)dealloc
{
    [super dealloc];
    [imageView removeFromSuperview];
    [View1 removeFromSuperview];
    [View2 removeFromSuperview];      
    [ScrollView removeFromSuperview];

    [imageView release];
    [View1 release];
    [View2 release];
    [ScrollView release];

    imageView = nil;
    View1 = nil;
    View2 = nil;
    ScrollView = nil;
}

please help me.Thanking you...

Ravi Kumar Karunanithi
  • 2,151
  • 2
  • 19
  • 41
HML
  • 103
  • 1
  • 9

3 Answers3

4

You need to call [super dealloc]; as the very last thing, not first. That's because [super dealloc] cleans up your object, and accessing instance variables afterwards is undefined behavior: anything can happen. For example, [super dealloc] could set all instance variables to nil, in which case the following release calls simply have no effect (and thus cause leaks). Also, there's no need to set the instance variables to nil since you're not going to use them anyway. So all you need is:

-(void)dealloc
{
    [imageView release];
    [View1 release];
    [View2 release];
    [ScrollView release];

    [super dealloc];
}

A few more notes: the removeFromSuperview calls are harmless but unnecessary, this is implicitly done by [super dealloc]. And you should stick to Apples naming conventions which in your case means you shouldn't start variable names with uppercase letters. So it should be scrollView instead of ScrollView.

DarkDust
  • 90,870
  • 19
  • 190
  • 224
1

No need to remove those subviews from superview, since anyhow you are going to release the superview itself.

You can make the dealloc as follows.

-(void)dealloc{

    [imageView release];
    [View1 release];
    [View2 release];
    [ScrollView release];

    imageView = nil;
    View1 = nil;
    View2 = nil;
    ScrollView = nil;

    [super dealloc];
}

Note that [super dealloc] is at the end (More info).

Community
  • 1
  • 1
Ilanchezhian
  • 17,426
  • 1
  • 53
  • 55
  • thank you aadhira...but why should i write [super dealloc] at the end?i mean if i write [super dealloc] at the top then what will happen and if i write at the end then what will happen? – HML Jun 04 '12 at 06:33
0

You might want to enable ARC in your projects. You won't need to release these objects anymore; the system will take care of (most of) your memory-management.

You can read more about ARC here: http://developer.apple.com/library/ios/#releasenotes/ObjectiveC/RN-TransitioningToARC/Introduction/Introduction.html

Z S
  • 7,039
  • 12
  • 53
  • 105
  • 1
    Turning on ARC in an existing project is a bit overkill if you just want to fix a simple memory leak. – DarkDust Jun 04 '12 at 06:37
  • But it's great if you're starting off on iOS development (like this person is) – Z S Jun 04 '12 at 19:12