title: How to set delegate for case: Message sent to deallocated instance
body: <p>When I login, I call the VC2 by segue from VC1</p>
  <pre><code>- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
      if ([[segue identifier] isEqualToString: @&quot;embeddedVC2&quot;]) {
          self.VC2 = [segue destinationViewController];
          self.VC2.delegate = self;
      }
    }
  </code></pre>
  <p>and I have the dealloc in VC1</p>
  <pre><code> -(void)dealloc{
     self.VC2.delegate=nil;
  }
  </code></pre>
  <p>The delegate in VC2 is declared as (nonatomic,assign)</p>
  <p>and in VC2, I'm performing a download operation, and when it finishes I'm calling</p>
  <pre><code>  [self.delegate downloadFinish:self.downloadData];
  </code></pre>
  <p>The problem is that by the time the download is finsihed, the dealloc in VC1 gets called , and its making the delegate in VC2 nil. So the delegate is nil, and  [self.delegate downloadFinish:self.downloadData]; doesnt work.</p>
  <p>If I remove the <code>self.VC2.delegate=nil</code> in the VC1 <code>dealloc</code> method, then I get the exception
  at the line:</p>
  <pre><code>   [self.delegate downloadFinish:self.downloadData];
  </code></pre>
  <p><em>message sent to deallocated instance</em> : as VC1 is deallocated and I can't do anything on it.</p>
  <p>What is the proper way of handling this scenario ?</p>
  <p><strong>Note</strong>: This only happens when I redo the procedure again.</p>
  <p><strong>Case 1</strong> : login -&gt; VC1 -&gt;VC2 works fine, delegate notifies me about the download finish</p>
  <p><strong>Case 2</strong> :<strong>no dealloc method in VC1:</strong></p>
  <p>login -&gt; VC1 -&gt; VC2 -&gt; logout -&gt;login -&gt; VC1 -&gt; VC2 (boom) crash-message sent to deallocated instance</p>
  <p><strong>Case 3</strong> :<strong>with dealloc in VC1 and self.VC2.delegate=nil in it:</strong></p>
  <p>login -&gt; VC1 -&gt; VC2 -&gt; logout -&gt;login -&gt; VC1 -&gt; VC2 nothing happens,as delegate is set to nil</p>
  <p>I tried using Zombie instrument, but I didnt understand a bit. I was confused by the long stack trace and was lost looking at the reference count and retain count numbers. I can post the stacktract in the instruments if you need.</p>
  <p><strong>Edit:</strong></p>
  <p>I changed the delegate to <code>nonatomic</code> and <code>weak</code> and removed the <code>dealloc</code> methods.</p>
  <p>and when I load <code>VC2</code> by segue , the VC2 delegate is not nil in <code>viewDidLoad</code>, but it turned to be <code>nil</code> by the point the download is finished, and at this point I'm still in VC2. I wonder what is making the delegate nil as I didn't move to another VC.</p>