Reputation: 11201
When I login, I call the VC2 by segue from VC1
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
if ([[segue identifier] isEqualToString: @"embeddedVC2"]) {
self.VC2 = [segue destinationViewController];
self.VC2.delegate = self;
}
}
and I have the dealloc in VC1
-(void)dealloc{
self.VC2.delegate=nil;
}
The delegate in VC2 is declared as (nonatomic,assign)
and in VC2, I'm performing a download operation, and when it finishes I'm calling
[self.delegate downloadFinish:self.downloadData];
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.
If I remove the self.VC2.delegate=nil
in the VC1 dealloc
method, then I get the exception
at the line:
[self.delegate downloadFinish:self.downloadData];
message sent to deallocated instance : as VC1 is deallocated and I can't do anything on it.
What is the proper way of handling this scenario ?
Note: This only happens when I redo the procedure again.
Case 1 : login -> VC1 ->VC2 works fine, delegate notifies me about the download finish
Case 2 :no dealloc method in VC1:
login -> VC1 -> VC2 -> logout ->login -> VC1 -> VC2 (boom) crash-message sent to deallocated instance
Case 3 :with dealloc in VC1 and self.VC2.delegate=nil in it:
login -> VC1 -> VC2 -> logout ->login -> VC1 -> VC2 nothing happens,as delegate is set to nil
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.
Edit:
I changed the delegate to nonatomic
and weak
and removed the dealloc
methods.
and when I load VC2
by segue , the VC2 delegate is not nil in viewDidLoad
, but it turned to be nil
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.
Upvotes: 0
Views: 147
Reputation: 10328
Make sure you either push a VC, present a VC, or add as a childViewController, this way the parent doesn't get deallocated. Otherwise if you are using tabbar for example, you need to make sure VC1 never gets set to nil.
I would rewrite the way you are adding VC's to your hierarchy if you are spending too much time trying to solve it.
Upvotes: 2