First of all: Thanks for all your help, comments, answers, suggestions...
Of course there was another strong
reference to the MyViewController
-object. But it wasn't that obvious, because it was not a property or instance variable.
In viewDidLoad
I did the following:
[[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationWillResignActiveNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) {
[self saveState];
}];
This should prevent data loss in case the user sends the app to the background. Of course the block captures the needed parts of its environment. In this case it captured self
. The block keeps self
alive until it (the block) gets destroyed, which is the case when e.g. [[NSNotificationCenter defaultCenter] removeObserver:self];
gets called. But, bad luck, this call is placed in the dealloc
method of MyViewController
which won't get called as long as the block exists...
The fix is as follows:
__weak MyViewController *weakSelf = self;
[[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationWillResignActiveNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) {
[weakSelf saveState];
}];
Now the block captures weakSelf
. This way it can't keep the MyViewController
-object alive and everything deallocs and works just fine.